每周获得过去1个月的总订单

时间:2014-02-13 05:25:59

标签: sql-server

我有一个“订单”表,其中包含订单发生时的列CreatedDate(datetime)。

今天是2014年2月13日。

如何获取每周过去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)

所以他们按升序排列。

1 个答案:

答案 0 :(得分: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