同时聚合计数和完整计数

Mos*_*atz 5 postgresql aggregate count

我有一个events这样的表:

create table events
(
    correlation_id char(26) not null,
    user_id        bigint,
    task_id        bigint not null,
    location_id    bigint,
    type           bigint not null,
    created_at     timestamp(6) with time zone not null,
    constraint events_correlation_id_created_at_user_id_unique
        unique (correlation_id, created_at, user_id)
);
Run Code Online (Sandbox Code Playgroud)
CREATE TABLE
Run Code Online (Sandbox Code Playgroud)

该表保存正在执行的任务的记录,如下所示:

insert into events (correlation_id, user_id, task_id, location_id, type, created_at)
values  ('01CN4HP4AN0000000000000001', 4, 58, 30, 0, '2018-08-17 18:17:15.348629+00'),
        ('01CN4HP4AN0000000000000001', 4, 58, 30, 1, '2018-08-17 18:17:22.852299+00'),
        ('01CN4HP4AN0000000000000001', 4, 58, 30, 99, '2018-08-17 18:17:25.535593+00'),
        ('01CN4J9SZ80000000000000003', 4, 97, 30, 0, '2018-08-17 18:28:00.104093+00'),
        ('01CN4J9SZ80000000000000003', 4, 97, 30, 98, '2018-08-17 18:28:49.04584+00'),
        ('01CN4J9SZ80000000000000003', 4, 97, 30, 99, '2018-08-17 18:29:09.01684+00'),
        ('01CN4JC1430000000000000004', 4, 99, 30, 0, '2018-08-17 18:29:12.963264+00'),
        ('01CN4JC1430000000000000004', 4, 99, 30, 3, '2018-08-17 18:29:47.83452+00'),
        ('01CN4JC1430000000000000004', 4, 99, 30, 98, '2018-08-17 18:31:01.86342+00'),
        ('01CN4JC1430000000000000004', 4, 99, 30, 99, '2018-08-17 18:32:09.272632+00'),
        ('01CN4KJCDY0000000000000005', 139, 97, 30, 0, '2018-08-17 18:50:09.725668+00'),
        ('01CN4KJCDY0000000000000005', 139, 97, 30, 3, '2018-08-17 18:50:11.842+00'),
        ('01CN4KJCDY0000000000000005', 139, 97, 30, 99, '2018-08-17 18:51:42.240895+00'),
        ('01CNC4G1Y40000000000000008', 139, 99, 30, 0, '2018-08-20 17:00:40.26043+00'),
        ('01CNC4G1Y40000000000000008', 139, 99, 30, 99, '2018-08-20 17:00:47.583501+00');
Run Code Online (Sandbox Code Playgroud)
INSERT 0 15
Run Code Online (Sandbox Code Playgroud)

该列的某些值type表示紧急情况。我可以使用这个简单的查询来计算在执行过程中每种类型的紧急情况发生的任务数量:

SELECT COUNT(DISTINCT correlation_id), type
FROM events
WHERE type IN (3, 5, 97, 98)
GROUP BY type;
Run Code Online (Sandbox Code Playgroud)
数数 类型
2 3
2 98
SELECT 2
Run Code Online (Sandbox Code Playgroud)

我还可以使用这个简单的查询来计算有多少任务在执行过程中发生了任何类型的紧急情况:

SELECT COUNT(DISTINCT correlation_id)
FROM events
WHERE type IN (3, 5, 97, 98);
Run Code Online (Sandbox Code Playgroud)
数数
3
SELECT 1
Run Code Online (Sandbox Code Playgroud)

问题是:有没有办法将这两个查询组合起来,以便我可以在单个查询中获取总数以及按类型细分?

我不能只将列相加count,因为一个correlation_id值可以有多个与其关联的紧急类型。在上面的示例中,correlation_id紧急情况总计有 3 个值,但添加该count列后将达到 4 个。

小提琴

mus*_*cio 8

你想要的是ROLLUP

SELECT COUNT(DISTINCT correlation_id), type
FROM events
WHERE type IN (3, 5, 97, 98)
GROUP BY ROLLUP (type);
Run Code Online (Sandbox Code Playgroud)