昨天,LastWeek,LastMonth Records

时间:2018-05-05 02:33:13

标签: sql sql-server

如何使用sql server中的startdate和enddate字段在单个查询中获取Yesterday,Last7Days,LastMonth。

Field1      Yesterday       Last7Days       LastMonth
------      ---------       ---------       ----------
row1        count(Records)  count(Records)  count(Records)
row2        count(Records)  count(Records)  count(Records)

由于

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select field1,
       sum(case when datecol >= dateadd(day, -2, cast(getdate() as date)) and
                     datecol < cast(getdate() as date)) 
                then 1 else 0
           end) as yesterday,
       sum(case when datecol >= dateadd(day, -8, cast(getdate() as date)) and
                     datecol < cast(getdate() as date)) 
                then 1 else 0
           end) as lastweek,
       sum(case when datecol >= dateadd(month, -1, cast(getdate() as date)) and
                     datecol < cast(getdate() as date)) 
                then 1 else 0
           end) as lastmonth                     
from t
group by field1;