繁体   English   中英

SQL分组结果与计数和累积计数

[英]SQL Grouped Results with Counts and Cumulative Counts

我的“用户”表中有以下数据:

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

您将为此使用窗口函数:

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);

您可以使用此查询。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM