Ini dapat dilakukan di server sql menggunakan UNPIVOT
dan kemudian PIVOT
. Versi Statis adalah tempat Anda mengetahui kolom yang akan diubah:
select *
from
(
select CaseId, EcoYear, val, item
from yourtable
unpivot
(
val
for Item in (NetInv, NetOil, NetGas)
)u
) x
pivot
(
max(val)
for ecoyear in ([2006], [2007], [2008], [2009], [2010], [2011],
[2012], [2013], [2014], [2015], [2016], [2017],
[2018], [2019], [2020])
) p
lihat SQL Fiddle dengan Demo
Versi Dinamis akan menentukan record saat dieksekusi:
DECLARE @colsPivot AS NVARCHAR(MAX),
@colsUnpivot as NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT distinct ',' + QUOTENAME(EcoYear)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name LIKE 'Net%'
for xml path('')), 1, 1, '')
set @query
= 'select *
from
(
select caseid, ecoyear, val, col
from yourtable
unpivot
(
val
for col in ('+ @colsunpivot +')
) u
) x1
pivot
(
max(val)
for ecoyear in ('+ @colspivot +')
) p'
exec(@query)
lihat SQL Fiddle dengan Demo