SQL Query返回按周,月和年分组的记录。没有记录的周数应该返回0

时间:2014-07-29 07:34:04

标签: sql sql-server sql-server-2012 group-by

鉴于以下数据:

ID      CreatedDate
ID1     2014-06-04 01:40:56.880
ID8     2014-06-05 00:27:02.403
ID6     2014-06-04 01:51:47.060
ID7     2014-06-05 00:25:35.187
ID4     2014-06-04 01:48:44.157
ID10    2014-06-05 00:28:33.993
ID43    2014-06-16 05:17:18.803
ID72    2014-06-20 04:00:07.733
.
.
.
Etc.

我需要编写一个查询,按周,月和年对记录进行分组。需要返回在特定周内创建的记录数的计数。输出应如下:

Week    Month   Year    Count
23         6    2014    16
24         6    2014    0
25         6    2014    7
26         6    2014    0
27         7    2014    25
28         7    2014    18  
.
.
.
etc.

如果一周没有记录,则计数应返回0.只有在执行查询后的过去12个月内创建的记录才应返回。查询将每周执行一次以生成报告。

1 个答案:

答案 0 :(得分:5)

演示目的我使用表名作为[DBO]。[FACTINTERNETSALES]和列[ORDERDATE] 对于你,Column将是[CreatedDate]。 Fyi,这是在SQL Server中完成的。

DECLARE @START INT,
        @END INT

SELECT @START   = CAST(CAST(MIN(ORDERDATE) AS DATETIME) AS INT) FROM [DBO].[FACTINTERNETSALES] 
SELECT @END     = CAST(CAST(MAX(ORDERDATE) AS DATETIME) AS INT) FROM [DBO].[FACTINTERNETSALES] 

--SELECT @START,@END

DECLARE @DATEDIM TABLE (ID INT IDENTITY(1,1) PRIMARY KEY, DATED DATETIME)
WHILE @START <= @END
BEGIN
    INSERT INTO @DATEDIM VALUES (CAST(@START AS DATETIME))
    SET @START = @START  + 1 
END

SELECT      LU.WEEK,LU.MONTH,LU.YEAR,ISNULL(MAIN.COUNT,0) [COUNT]
FROM        (
            SELECT      DATEPART(WEEK,DATED) [WEEK],DATEPART(MONTH,DATED) [MONTH],DATEPART(YEAR,DATED) [YEAR] 
            FROM        @DATEDIM
            GROUP BY    DATEPART(WEEK,DATED),DATEPART(MONTH,DATED),DATEPART(YEAR,DATED)) LU
LEFT JOIN
            (
            SELECT  [YEAR],[MONTH],[WEEK],COUNT(*) [COUNT] FROM
            (SELECT DATEPART(YEAR,ORDERDATE) [YEAR],
                    DATEPART(MONTH,ORDERDATE) [MONTH],
                    DATEPART(WEEK,ORDERDATE) [WEEK]
            FROM    [DBO].[FACTINTERNETSALES] ) LUINNER
            GROUP BY [YEAR],[MONTH],[WEEK]) MAIN 
ON
            LU.MONTH = MAIN.MONTH AND
            LU.YEAR = MAIN.YEAR AND
            LU.WEEK = MAIN.WEEK
ORDER BY    LU.YEAR,LU.MONTH,LU.WEEK

结果:(只有部分结果)

enter image description here