问题
Given the following data:
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.
I need to write a query that will group records by week, month, and year. A count of the number of records that were created in a particular week needs to be returned. The output should be as follows:
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.
Where a week has no records the count should return 0. Only records that were created within the past 12 months from the time the query is executed should be return. The query will be executed each week to produce a report.
回答1:
Demo purpose I am using the Table name as [DBO].[FACTINTERNETSALES] and the column [ORDERDATE] For you the Column will be [CreatedDate]. Fyi, This is done in 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
Result: (Only a portion of result)
来源:https://stackoverflow.com/questions/25010284/sql-query-to-return-records-grouped-by-week-month-and-year-weeks-with-no-reco