Esto se puede hacer en el servidor sql usando tanto un UNPIVOT
y luego un PIVOT
. Una versión estática es donde conoce las columnas para transformar:
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
ver SQL Fiddle con demostración
Una versión dinámica determinará los registros en ejecución:
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)
ver SQL Fiddle con demostración