1

我正在编写一个查询来分解在给定年份中每周订购的零件数量。但是,零件订单表中只有 1 个日期列。

这是我想要完成的事情:

PartNo    PartDesc    Type       Week1    Week2    Week3 ...
------------------------------------------------------------
000001    Shoe        Black         54       44       6
000001    Shoe        White         64       33       7
000002    GLove       Black          1       22       8
000002    Glove       White          7       11       9

这是表格布局

PartsOrderTable
----------------
PartNo
PartDesc
PartType
Qty
DateField

到目前为止,这是我的查询,它适用于第 1 周,我不确定如何将其他周附加到结果的末尾?

SELECT PartNo, PartDesc, Type, SUM(Qty) as Week1 
FROM PartsOrderTable
WHERE DateField >= '1/1/2013'
AND DateField <= '12/31/2013'
And DATEPART(ww, DateField) = 1
GROUP BY PartNo, PartDesc, Type, DATEPART(ww, DateField)
ORDER BY PartNo, Week1

这是我目前得到的:

PartNo    PartDesc    Type       Week1
----------------------------------------
000001    Shoe        Black         54
000001    Shoe        White         64
000002    GLove       Black          1
000002    Glove       White          7

是否可以在一个简单的查询中添加每周订购的数量?

4

1 回答 1

4

您可以使用该PIVOT函数来执行此操作,因此代码将类似于以下内容:

select *
from
(
  SELECT PartNo, PartDesc, Type, Qty,
    'Week'+cast(DATEPART(ww, DateField) as varchar(2)) WeekNo
  FROM PartsOrderTable
  WHERE year(DateField) = 2013
) d
pivot
(
  sum(qty)
  for WeekNo in (Week1, Week2, Week3, Week4)
) piv

请参阅SQL Fiddle with Demo

如果您有未知数量的列,或者想要传递一个日期范围,那么您可以使用动态 sql 来创建结果。我强烈建议您在动态返回日期时限制列数,您要确保不会返回太多列:

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

select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Week'+cast(DATEPART(ww, DateField) as varchar(2))) 
                    from PartsOrderTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT PartNo, PartDesc, Type,' + @cols + ' 
            from 
            (
                SELECT PartNo, PartDesc, Type, Qty,
                  ''Week''+cast(DATEPART(ww, DateField) as varchar(2)) WeekNo
                FROM PartsOrderTable
                WHERE year(DateField) = 2013
            ) x
            pivot 
            (
                sum(qty)
                for WeekNo in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

于 2013-04-04T22:38:12.617 回答