带有计数和累积计数的SQL分组结果

时间:2017-09-24 14:56:04

标签: sql sql-server group-by count sum

我的用户'我有以下数据:表:

user_id | create_timestamp
1         2017-08-01
2         2017-08-01
3         2017-08-02
4         2017-08-03
5         2017-08-03
6         2017-08-03
7         2017-08-04
8         2017-08-04
9         2017-08-04
10        2017-08-04

我想创建一个包含三列的SQL查询: 1. create_timestamp的分组结果 2.按日期计算的结果 3.累计计数作为日期继续。

以下是结果集的样子:

create_timestamp daily cumulative
2017-08-01         2      2
2017-08-02         1      3
2017-08-03         3      6
2017-08-04         4      10

2 个答案:

答案 0 :(得分:2)

您可以使用窗口函数:

select create_timestamp, count(*) as cnt,
       sum(count(*)) over (order by create_timestamp) as cumulative
from t
group by create_timestamp
order by create_timestamp;

此功能在SQL Server 2012 +中可用。

注意:您可能需要从时间戳中提取日期:

select convert(date, create_timestamp) as dte, count(*) as cnt,
       sum(count(*)) over (order by convert(date, create_timestamp)) as cumulative
from t
group by convert(date, create_timestamp)
order by convert(date, create_timestamp);

答案 1 :(得分:1)

您可以使用此查询。

DECLARE @UserLog TABLE (user_id INT , create_timestamp DATE)
INSERT INTO @UserLog
VALUES
(1,'2017-08-01'),
(2,'2017-08-01'),
(3,'2017-08-02'),
(4,'2017-08-03'),
(5,'2017-08-03'),
(6,'2017-08-03'),
(7,'2017-08-04'),
(8,'2017-08-04'),
(9,'2017-08-04'),
(10,'2017-08-04')

;WITH T AS (
    SELECT create_timestamp, COUNT(*) daily  FROM @UserLog
    GROUP BY create_timestamp)
    SELECT 
        create_timestamp, 
        daily, 
        SUM(daily) OVER( ORDER BY create_timestamp ASC  
                            ROWS UNBOUNDED PRECEDING ) cumulative  
FROM T

结果

create_timestamp daily       cumulative
---------------- ----------- -----------
2017-08-01       2           2
2017-08-02       1           3
2017-08-03       3           6
2017-08-04       4           10