SQL - 在PIVOT中使用变量列分组

时间:2015-07-27 17:13:59

标签: sql sql-server sql-server-2008

我正在尝试按日期对输出进行分组。对于此表中的每个条目,每个独特样式(N个样式)都有订单明细行,其中包含订单日期和发货数量。我的目标是在每行中输出一个带有日期,样式标题和相关订单日期以及出货总计的输出。现在,我为每个细节线而不是汇总排了一行。我尝试了group by order_date, '+@PivotColumns+',但这并不奏效。我当然不能做group by order_date。我是否需要对结果进行另一次查询?

DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(rtrim(style))
FROM (SELECT DISTINCT style FROM opendet where isnumeric(style)=1 and season='ESSENTIALS') AS stylepivot

SET   @SQLQuery = N'
select
order_date,'+@PivotColumns+'
FROM opendet
PIVOT(
 SUM(SHIP_QTY)
 FOR style IN ('+@PivotColumns+')
) AS P'

EXEC sp_executesql @SQLQuery

这就是我现在所得到的:

order_date  15080   15082   15083   
2012-12-12  1       NULL    NULL
2012-12-13  NULL    1       NULL
2012-12-13  NULL    2       NULL
2012-12-14  NULL    NULL    1
2012-12-14  NULL    NULL    1
2012-12-15  NULL    NULL    NULL
2012-12-16  1       NULL    NULL
2012-12-16  4       NULL    NULL
2012-12-16  3       NULL    NULL

这就是我想要的:

order_date  15080   15082   15083   
2012-12-12  1       NULL    NULL
2012-12-13  NULL    3       NULL
2012-12-14  NULL    NULL    2
2012-12-15  NULL    NULL    NULL
2012-12-16  8       NULL    NULL

这是源表的修剪摘录,(还有更多列):

order_date  style   season      ship_qty
2014-01-06  15082   ESSENTIALS  2.00
2014-01-06  15082   ESSENTIALS  1.00
2014-01-06  15082   ESSENTIALS  1.00
2014-01-06  15082   ESSENTIALS  2.00
2014-01-08  15080   ESSENTIALS  1.00
2014-01-08  15080   ESSENTIALS  1.00
2014-01-08  15080   ESSENTIALS  1.00
2014-01-08  15080   ESSENTIALS  1.00
2014-01-08  15082   ESSENTIALS  2.00
2014-01-08  15082   ESSENTIALS  2.00
2014-01-08  15082   ESSENTIALS  2.00

1 个答案:

答案 0 :(得分:2)

我认为你只需要在聚合之前预先聚合到样式/日期级别:

DECLARE   @SQLQuery AS NVARCHAR(MAX)
DECLARE   @PivotColumns AS NVARCHAR(MAX)

SELECT   @PivotColumns= COALESCE(@PivotColumns + ',','') + QUOTENAME(rtrim(style))
FROM (SELECT DISTINCT style FROM opendet where isnumeric(style)=1 and season='ESSENTIALS') AS stylepivot

SET   @SQLQuery = N'
select
order_date,'+@PivotColumns+'
FROM (SELECT order_date,style, SUM(Ship_Qty) AS Ship_Qty
      FROM opendet
      GROUP BY order_date,style
      )sub
PIVOT(
 SUM(SHIP_QTY)
 FOR style IN ('+@PivotColumns+')
) AS P'

EXEC sp_executesql @SQLQuery