SQL Server累计用户数天数

时间:2017-07-29 18:53:19

标签: sql sql-server azure-sql-database

我有一个user表,如下所示:

id | createdAt                      | name  ...
---+--------------------------------+-----------
1    2017-04-12 13:19:37.287 +00:00    X
2    2017-04-12 13:19:37.287 +00:00    Y
3    2017-04-12 13:19:37.287 +00:00    Z
4    2017-04-13 13:19:37.287 +00:00    T
5    2017-04-13 13:19:37.287 +00:00    W
6    2017-04-14 13:19:37.287 +00:00    W
7    2017-04-14 13:19:37.287 +00:00    W

我需要的是每天的累计用户数,例如:

day        | count
-----------+--------
2017-04-12    3
2017-04-13    5
2017-04-14    7

我尝试使用此SQL语句对天进行分组,但它只会获取当天不记录的记录

SELECT 
    CAST(createdAt AS DATE) AS date, COUNT(*) AS userCount 
FROM 
    dbo.Users 
GROUP BY 
    CAST(createdAt AS DATE) 
ORDER BY 
    CAST(createdAt AS DATE) DESC

感谢任何帮助

由于

1 个答案:

答案 0 :(得分:7)

在SQL Server 2012+中,您将使用累积总和:

SELECT CAST(createdAt AS DATE) as date, COUNT(*) as userCount,
       SUM(COUNT(*)) OVER (ORDER BY CAST(createdAt AS DATE)) as cumulative_count
FROM dbo.Users u
GROUP BY CAST(createdAt AS DATE)
ORDER BY CAST(createdAt AS DATE) DESC;

在早期版本中,需要另一种方法,例如相关子查询:

WITH u as (
      SELECT CAST(createdAt AS DATE) as date, COUNT(*) as userCount
      FROM dbo.Users u
      GROUP BY CAST(createdAt AS DATE)
     )
SELECT u.*,
       (SELECT SUM(usrCount)
        FROM u u2
        WHERE u2.date <= u.date
       ) as cumulative_count
FROM u
ORDER BY date DESC;