sql >> Database teknologi >  >> RDS >> Sqlserver

Dynamisk pivottabel i SQL Server

Dette kan gøres i sql server ved at bruge både en UNPIVOT og derefter en PIVOT . En statisk version er, hvor du kender kolonnerne, der skal transformeres:

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

se SQL Fiddle with Demo

En dynamisk version bestemmer posterne ved udførelse:

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)

se SQL Fiddle with Demo




  1. Opretter du en logningshandler for at oprette forbindelse til Oracle?

  2. Reducer SQL Server-licensomkostninger

  3. Generer DEFAULT-værdier i en CTE UPSERT ved hjælp af PostgreSQL 9.3

  4. Hent alle datoer mellem to datoer i SQL Server