繁体   English   中英

在SQL查询中获取零计数

[英]get zero counts in sql query

以前已经处理过该主题,但是仍然找不到我的解决方案。 我正在计算服务开启/关闭的时间。 如果该服务从未关闭过(例如,对于id = 7182),则该服务的表中不存在status =='off'。

如下面的示例所示,如何获得计数== 0的计数? 我已经突出显示了我需要但无法显示的行的示例。

提前多谢

PS:我一直在玩游戏,但是没有运气,或者现在不正确地使用它。

SELECT id, status, count(*)
from history 
group by id, status
order by id, status; 

  id  | status | count 
------+--------+-------
 7182 | on     |    50
 7182 | off    |     0 <-- Not shown in the output as there is no id=7182 with status=off
 7183 | on     |    50
 7183 | off    |     0 <-- Not shown in the output as there is no id=7183 with status=off
 7184 | on     |    49
 7184 | off    |     1
SELECT id, status, count(*)
from history 
group by id, status
UNION ALL
SELECT id, 'OFF', 0
from history
where id not in (select id from history where status = 'OFF')
order by id, status; 

据我了解,现在不显示count = 0,而您想在结果中获取它。 尝试一下:

SELECT id, status, count(*) as c
from history 
group by id, status
having c >= 0
order by id, status;

一种方法是使用conditional sum并获得开/关计数为

select
id,
sum( case when status = 'on' then 1 else 0 end)  as on_count,
sum( case when status = 'off' then 1 else 0 end ) as off_count
from history
group by id

表格中缺少某些ID /状态组合,但您想查看它们。 解决方案是使用交叉联接创建它们:

select i.id, s.status, count(*)
from (select distinct id from history) as i
cross join (select distinct status from history) as s
left join history h on h.id = i.id and h.status = s.status
group by i.id, s.status
order by i.id, s.status;

顺便说一句:当列ID不是表中记录的唯一ID时,给列ID命名是个坏主意。

暂无
暂无

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

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