数据透视表与日期顺序中的动态列

时间:2016-04-21 04:53:57

标签: tsql dynamic pivot unpivot

我有一个数据透视表,为每行创建2列,我希望按日期顺序排列。

Below is the data in the raw format
-------------------------------------------------------------
partnum   | period  | TotalQty     |     ToldSold

005483-6  | 2015-08 | 100.00000000 |    389.379000

0551105   | 2015-08 | 10.00000000  |    4560.773000

0CT202305 | 2015-09 | 4.00000000   |    2285.430800

0CTR00905 | 2015-10 | 2.00000000   |    654.305400

183386-32 | 2016-01 | 20.00000000  |    75.060400

24-175UV50| 2016-03 | 450.00000000 |    42.723000

我有以下代码来生成动态数据透视表

DECLARE @cols AS NVARCHAR(MAX),
@colsName AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(period +'_'+c.col)
                  from #orderhistory
                  cross apply 
                  (
                    select 'TotalQty' col
                    union all
                    select 'ToldSold'
                  ) c
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

select @cols



select @colsName 
= STUFF((SELECT distinct ', ' + QUOTENAME(period +'_'+c.col) 
           +' as ['
           + period + case when c.col = 'TotalQty' then ' QtySold]' else 'Total $ Sold]' end
         from #orderhistory
         cross apply 
         (
            select 'TotalQty' col
            union all
            select 'ToldSold'
         ) c
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

select @colsName

set @query 
= 'SELECT partnum, ' + @colsName + ' 
 from 
 (
  select 
    partnum, 
    period +''_''+col col, 
    value
  from
  (
    select partnum, 
      period,
      cast(TotalQty as numeric(10, 2)) TotalQty,
      cast(ToldSold as numeric(10, 2)) ToldSold
    from #orderhistory
  ) src
  unpivot
  (
    value
    for col in (TotalQty, ToldSold)
  ) unpiv
 ) s
 pivot 
 (
   sum(value)
   for col in (' + @cols + ')
 ) p 
 order by partnum'

execute(@query)

它创建如下的数据

partnum 2016-02 QtySold 2015-08Total $ Sold 2015-11Total $ Sold 2015-12 QtySold

005483-10   NULL    NULL    NULL    100.00

005483-12   NULL    NULL    1249.68 450.00

005483-14   NULL    NULL    NULL    70.00

005483-2    NULL    NULL    1234.19 350.00

005483-3    10.00   NULL    NULL    NULL

我希望看到标题符合日期顺序

partnum | 2015-08 QtySold | 2015-08 Total $ Sold | 2015-09 QtySold | 2015-09 Total $ Sold........

直到我到达本月为止。

我想我需要在某个地方添加订单,我只是不知道在哪里。这是我的第一个多列动态数据透视表,所以我有点迷失。我尝试的任何地方都给了我一些错误。

非常感谢任何帮助!!

1 个答案:

答案 0 :(得分:0)

您可以订购@colNames数据..

SELECT  @colsName = STUFF((
    SELECT  DISTINCT
            ', ' 
            + QUOTENAME(period + '_' + c.col) 
            + ' as [' 
            + period 
            + CASE WHEN c.col = 'TotalQty' THEN ' QtySold]' ELSE 'Total $ Sold]' END
    FROM    #orderhistory
            CROSS APPLY (SELECT 'TotalQty' col UNION ALL SELECT 'ToldSold') c
--ORDER BY HERE
    ORDER BY period, c.col
    FOR XML PATH(''), TYPE
).value('.','NVARCHAR(MAX)'),1,1,'')