Dynamic Pivot Table in SQL Server

前端 未结 1 845
别那么骄傲
别那么骄傲 2020-11-27 23:14

Hello I have the following table and I want to pivot the EcoYear to be across the top but there aren\'t a set amount of years and the years could start anytime. In addition,

相关标签:
1条回答
  • 2020-11-27 23:24

    This can be done in sql server using both an UNPIVOT and then a PIVOT. A Static version is where you know the columns to transform:

    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
    

    see SQL Fiddle with Demo

    A Dynamic Version will determine the records on execution:

    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)
    

    see SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题