如何在sql server中获取最近7天的日期计数?

时间:2017-05-09 06:10:39

标签: sql-server

我为sql server中的每日最近7天用户关注者数量创建了一个查询。我写了一个查询,但没有给出表的预期输出。现在只是在过去7天给出计数而不给出日期。在下面写下我的查询并告诉我我的错误在哪里。

这是我的查询=>

DECLARE @my_date DATE = CAST(GETDATE() AS DATE)
SELECT  
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -7, @my_date) THEN 1 ELSE 0 END) AS date1Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -6, @my_date) THEN 1 ELSE 0 END) AS date2Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -5, @my_date) THEN 1 ELSE 0 END) AS date3Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -4, @my_date) THEN 1 ELSE 0 END) AS date4Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -3, @my_date) THEN 1 ELSE 0 END) AS date5Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -2, @my_date) THEN 1 ELSE 0 END) AS date6Count,
SUM(CASE WHEN CAST(InsertDateTime AS DATE) = DATEADD(DAY, -1, @my_date) THEN 1 ELSE 0 END) AS date7Count
FROM
UserFollower
WHERE
InsertDateTime BETWEEN DATEADD(DAY, -7, GETDATE()) AND DATEADD(DAY, -1, GETDATE())

当前输出=>

date1Count | date2Count | date3Count | date4Count | date5Count | date6Count | date7Count
 10            05           20           10           30            50          40

预期输出=>

Expected o/p =>

DateColumn | Count
09-05-2017    10
08-05-2017    05
07-05-2017    20
06-05-2017    10
05-05-2017    30
04-05-2017    50
03-05-2017    40

任何人都知道如何在sql server中执行此任务请告诉我。

2 个答案:

答案 0 :(得分:1)

在查询结尾处不能使用 GROUPBY 子句吗?

GROUP BY DateColumn

答案 1 :(得分:1)

您可以像这样使用APPLY

SELECT CAST(dateadd(day, T.i, getdate()) AS Date) AS DateColumn, uf.TotalCount 
FROM (VALUES (0), (-1), (-2), (-3), (-4), (-5), (-6)) AS T(i)
OUTER APPLY 
(
   SELECT Count(InsertDateTime) AS TotalCount
   FROM UserFollower
   WHERE Datediff(day,UserFollower.InsertDateTime, dateadd(day, T.i, getdate())) = 0 
) uf