我有这个查询,它根据定义的时间间隔选择每个“消息代码”的计数。
expect()
条目输出
SELECT coalesce(count(case when messagecode = 'F-100' then 'F-100' end), 0) as fixed,
coalesce(count(case when messagecode = 'H-100' then 'H-100' end), 0) as hope,
coalesce(count(case when messagecode = 'G-100' then 'G-100' end), 0) as good,
coalesce(count(case when messagecode = 'T-100' then 'T-100' end), 0) as todo
FROM messages WHERE messagetime >= current_timestamp - ('5' * interval '1 minute')
我想做类似的事情但是要选择具有此消息代码的唯一ID的数量,我知道我应该从做什么开始
fixed: 115,
hope: 334,
good: 1045,
todo: 6000
但我的问题是,我还不知道如何在同一查询的多个条件下执行此操作。预期产出:
SELECT coalesce(count(DISTINCT id), 0) ...
我将如何实现它?
答案 0 :(得分:1)
查询可能如下所示:
SELECT coalesce(count(distinct case when messagecode = 'F-100' then id end), 0) as fixed,
coalesce(count(distinct case when messagecode = 'H-100' then id end), 0) as hope,
coalesce(count(distinct case when messagecode = 'G-100' then id end), 0) as good,
coalesce(count(distinct case when messagecode = 'T-100' then id end), 0) as todo
FROM messages WHERE messagetime >= current_timestamp - ('5' * interval '1 minute')