如何动态地每月透视数据?

时间:2019-06-27 14:55:42

标签: sql sql-server tsql

我正在检查一家公司的专营店或自营店的订单数量。它们被放入日期差类别。这是查询和结果作为说明:

SELECT [Order-Delivery Difference], [Type], COUNT(DISTINCT OrderId) AS [Number of Orders]
FROM (SELECT DDIFF AS [Order-Delivery Difference], Franchise AS [Type], OrderId, [Net Value]
        FROM joined
        GROUP BY DDIFF, FRANCHISE, OrderId, [Net Value]
      ) AS subquery
GROUP BY [Order-Delivery Difference], [Type]
HAVING SUM([Net Value]) > 0
ORDER BY [Order-Delivery Difference]
;

enter image description here

我的表中有一个Date类型的列,我们称之为DateColumn。从理论上讲,我可以在任何给定的特定时间过滤此结果。

...
(SELECT DDIFF AS [Order-Delivery Difference], Franchise AS [Type], OrderId, [Net value]
    FROM joined
    WHERE DATEPART(year, [DateColumn]) = 2017 AND DATEPART(month, [DateColumn]) = 1
    GROUP BY DDIFF, FRANCHISE, OrderId, [Net Value]
) AS subquery
...

但是我想针对“日期”列中可用的每个不同月份的日期调整此结果,例如:

enter image description here

我的问题是: 我可以创建一个像这样的数据透视表,在表的开头添加另一列吗?还是应该为每个不同的O-D差异类别创建数据透视表?有可行的方法吗?

还有一种程序解决方案来创建具有所有不同月份日期的列,以将其作为数据透视功能的动态属性集吗?

1 个答案:

答案 0 :(得分:2)

也许这会有所帮助

示例

Declare @SQL varchar(max) = '
Select *
From (
        Select [Order-Delivery Difference] = DDIFF
             , [Type]  = Franchise 
             , [Value] = COUNT(DISTINCT OrderId)
             , [Item]  = left(DateColumn,7)
        From JOINED
        Group By DDIFF,Franchise,left(DateColumn,7)
     ) A
 Pivot (sum(Value) For [Item] in (' + Stuff((Select Distinct ',' + QuoteName(left(DateColumn,7)) From  JOINED Order By 1 For XML Path('')),1,1,'')  + ') ) p
 Order By [Order-Delivery Difference]
         ,Type
'

--Print @SQL
Exec(@SQL);

示例数据如下

enter image description here

结果看起来像这样

enter image description here

  

经过编辑-专为直属专栏

用于STUFF部分

Select Distinct ',' + QuoteName(left(DateColumn,7)) From  #JOINED

生成

(No column name)
,[2017-01]
,[2017-02]

添加For XML时,我们将获得一个XML字符串

,[2017-01],[2017-02]

然后STUFF(...,1,1,'')删除前导逗号,该逗号成为PIVOT列

[2017-01],[2017-02]