如何从上一期间获取相同的表格信息

时间:2016-07-23 18:32:44

标签: sql sql-server tsql

我有以下SQL查询:

DECLARE @startdate datetime
DECLARE @enddate datetime

/* HARD CODE 1 WEEK DATA */
SET @startdate = '2016-07-10 00:00:00'
SET @enddate = DATEADD(DAY, 7, @startdate)
SET @enddate = DATEADD(MINUTE, -1, @enddate)
/* HARD CODE 1 WEEK DATA */

SELECT COUNT(0) as registered
FROM member_request ma
WHERE ma.createddate BETWEEN @startdate AND @enddate

这返回在该时间周期中注册的总记录,我想在同一结果中获得另一列,这些列将为我提供总记录但前一周。

我知道我可以做额外的选择和UNION ALL他们但也许有更好的方法来做。

有任何线索吗?

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

SELECT 
   COUNT(CASE WHEN ma.createddate 
          BETWEEN @startdate AND @enddate THEN 1 END) AS current_week
  ,COUNT(CASE WHEN ma.createddate 
          BETWEEN @startdate - 7 AND @enddate - 7 THEN 1 END) AS prev_week
FROM member_request ma
WHERE ma.createddate BETWEEN @startdate - 7 AND @enddate;

WHERE - 过滤2周范围

COUNT(CASE WHEN ... END)仅计算1周范围内的行数

答案 1 :(得分:1)

只需减去一周:

SELECT COUNT(*) as registered
FROM member_request ma
WHERE ma.createddate BETWEEN DATEADD(week, -1, @startdate) AND DATEADD(week, -1, @enddate);

如果要在同一查询中使用两者,则使用条件聚合

select sum(case when ma.createddate BETWEEN @startdate AND @enddate then 1 else 0
           end) as thisweek,
       sum(case when ma.createddate BETWEEN DATEADD(week, -1, @startdate) AND DATEADD(week, -1, @enddate) then 1 else 0
           end) as lastweek
from member_request ma
where ma_createddate >= DATEADD(week, -1, @startdate);

注意:将between与日期/时间值一起使用。 Aaron Bertrand有一个信息丰富的博客,关于为什么不这样做,What do BETWEEN and the devil have in common?