枢纽DATEPART(星期,日期)

时间:2018-09-12 10:22:55

标签: sql tsql pivot

我有一个这样的桌子

mytable

date       | value
2018.09.12 |  1
2018.09.11 |  2
2018.09.10 |  3

我需要查询以返回最近六周的sum(value)。就是这样。

week# | value
 37   |  6
 36   |  0
 35   |  0
 34   |  8
 33   |  9
 32   |  10
 31   |  11

我有一个查询来返回每周的总值。

SELECT Sum(Value) AS Sumvalue,  DATEPART(wk, date) AS [weekNo]
FROM mytable
WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND  GETDATE() 
GROUP BY DATEPART(wk, date)

但这一周不能处理零值。

如何编写透视查询以获取格式?

我的尝试;

SELECT *
FROM (
           SELECT Value,  DATEPART(wk, date) AS [weekNo]
           FROM mytable
           WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND  GETDATE() 
     ) As sourcetable
PIVOT
(
    Sum(Value) for DATEPART(wk, date) IN (SELECT date FROM mytable where date between 
                            DATEADD(DAY, -42, GETDATE()) and   GETDATE())
) AS pivotable

我正在接近关键字的语法错误。我怎样才能把这六个星期变成关键状态?

1 个答案:

答案 0 :(得分:1)

找到了部分解决方案!

SELECT *
FROM (
           SELECT Value,  DATEPART(wk, date) AS [weekNo]
           FROM mytable
           WHERE Date BETWEEN DATEADD(DAY, -42, GETDATE()) AND  GETDATE() 
     ) As sourcetable
PIVOT
(
    Sum(Value) for [week] IN ([1], [2], [3], ... ,[54])
) AS pivotable

这是局部的,因为它是一种for语句的硬编码,无法控制查询中不必要的星期。