sql server - sql table row - column conversion -
i have following table:
how convert above table below structure? tried using pivot table couldn't work.
you need have sql pivot.
check this fiddle
and code:
select * ( select prodname, pcode, biiledamt product ) p pivot ( sum (biiledamt) prodname in ([prod1],[prod2],[prod3],[prod4]) ) pvt
if not know beforehand columns can check fiddle dynamically generates columns use.
the code is:
declare @cols varchar(max), @query varchar(max) set @cols = stuff((select distinct ',[' + prodname +']' product c xml path(''), type ).value('.', 'varchar(max)') ,1,1,'') set @query = ' select * ( select prodname, pcode, biiledamt product ) p pivot ( sum (biiledamt) prodname in (' + @cols + ') ) pvt ' exec(@query)
Comments
Post a Comment