在sql查询中获得零计数

时间:2014-12-12 10:37:53

标签: sql count zero

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

如何计算关闭== 0,如下例所示? 我已经突出显示了我需要但无法显示的行的示例。

提前多多感谢,

PS:我一直在玩coalesce,但没有运气,或者现在没有正确使用它。

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

4 个答案:

答案 0 :(得分:0)

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; 

答案 1 :(得分:0)

如果我理解,现在不显示count = 0,并且你想在结果中得到它。试一试:

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

答案 2 :(得分:0)

一种方法是使用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

答案 3 :(得分:0)

表格中缺少某些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,则列出一个名称是个坏主意。