2014-02-13 52 views
1

我有一個「訂單」表,其中包含創建日期(日期時間)列的訂單發生時間。每週獲得最後1個月的總訂單

今天是2月13日,2014年

如何獲得總記錄過去4周每週。

它應該返回是這樣的:

PerDate  Total 
2014-01-26 13 <--- sunday 
2014-02-02 24 <--- sunday 
2014-02-09 33 <--- sunday 
2014-02-13 35 <--- this is today 

13 from the first record is the total record from 2014-01-20 00:00:00 AM (monday) to 2014-01-26 12:00:00 PM (sunday) 
24 from the 2nd record is the total record from 2014-01-27 00:00:00 AM (monday) to 2014-02-02 12:00:00 PM (sunday) 
33 from the 3rd record is the total record from 2014-02-03 00:00:00 AM (monday) to 2014-02-09 12:00:00 PM (sunday) 
35 from the 4th record is the total record from 2014-02-10 00:00:00 AM (monday) to 2014-02-13 (today) 

所以他們是按升序排列。

+0

如果第一個記錄是從週日到星期日,再從星期天到星期日的第二個紀錄,那麼週日不會計算兩次? – Raj

+0

你爲什麼從2014-01-19算起?如果今天是2014-02-13,那麼上個月應該從2014-01-13開始。或者你只需​​要最後4周? – valex

+0

@Raj對不起,我的意思是每個星期的「FROM」部分應該是星期一00:00 AM。我編輯過它。 –

回答

1

您應該使用DATEPART(dw,CreatedDate)功能通過這個字段來計算開始和每個CreatedDate本週結束的日期,然後就組:

WITH T AS 
(
    SELECT 
     cast(floor(cast(CreatedDate as float)) as datetime) 
      -DATEPART(dw,CreatedDate)+1 as BeginOfweek,   
     cast(floor(cast(CreatedDate as float)) as datetime) 
      -DATEPART(dw,CreatedDate)+8 as EndOfWeek 
    FROM ORDERS 
    WHERE cast(floor(cast(CreatedDate as float)) as datetime) BETWEEN 
     DATEADD(WEEK,-4,GETDATE()) 
     AND 
     GETDATE() 

) 

SELECT 
BeginOfWeek, 
MIN(CASE WHEN GETDATE()<EndOfWeek 
       THEN GETDATE() 
       ELSE EndOfWeek 
     END) as EndOfWeek, 
Count(*) as OrdersCount 
FROM T 
Group by BeginOfWeek 

SQLFiddle demo

+0

對不起,我只是編輯帖子。你能更新你的嗎? –

+0

即時使用SQL Server 2005順便說一句,它返回有點兒不對 BeginOfWeek \t \t EndOfWeek OrdersCount 2014年1月13日10:32:40.523 \t 2014年1月20日10:32:40.523 2014年1月13日15: 50:30.573 \t慢速英語15:50:30.573 2014年1月13日16:33:06.880 \t慢速英語16:33:06.880 是因爲有一次我創建日期? –

+0

@ user974130 - 我改變了答案,只從'CreatedDate'中提取DATE部分。 – valex