具有动态日期的SQL Pivot

时间:2018-06-25 18:25:48

标签: sql

我正在尝试创建一个报告,该报告在过去4周中按项目每周汇总总销售额。例如:

|-Item-|-1Week-|-2Weeks-|-3Weeks-|-4Weeks-|
|-Pens-|---100-|---1000-|----800-|------0-|
|Pencil|-----0-|----600-|---1500-|---2000-|

以下查询恰好返回了我对前一周的期望,但是,在更改查询以分别对前四个星期进行汇总时,遇到了障碍。

SELECT        itemmast.itemcode, itemmast.description, itemmast.packsize, SUM(sodetail.order_quantity) AS qtyweek1
FROM            dbo.soheader AS soheader INNER JOIN
                         dbo.sodetail AS sodetail ON soheader.invoice_number = sodetail.invoice_number INNER JOIN
                         dbo.itemmast AS itemmast ON sodetail.itemcode = itemmast.itemcode
WHERE        (soheader.so_issue_datetime > DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0)) AND (soheader.so_issue_datetime < DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0))
GROUP BY itemmast.itemcode, itemmast.description, itemmast.packsize, sodetail.order_uomid

我了解了数据透视表的基础知识(因为我对SQL来说还很陌生,所以不必使用任何数据透视表),但是我不确定如何将动态日期范围转换为列并实现目标。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

通过将下面的示例添加到我需要的每周的select语句中,只需调整DATEDIFF参数,就可以解决我的问题。

isnull(SUM(CASE WHEN (soheader.so_issue_datetime > DATEADD(wk, DATEDIFF(wk, 6, GETDATE()), 0)) AND (soheader.so_issue_datetime < DATEADD(wk, DATEDIFF(wk, 0, GETDATE()), 0)) THEN sodetail.order_quantity END),0) AS "1 Week"