To lze provést na serveru SQL pomocí UNPIVOT
a poté PIVOT
. Ve statické verzi znáte sloupce, které se mají transformovat:
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
viz SQL Fiddle with Demo
Dynamická verze určí záznamy o provedení:
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)
viz SQL Fiddle with Demo