在sql查询中获取零计数
这个话题以前已经讨论过了,但我仍然找不到解决办法。 我正在计算服务的开/关次数。 如果服务从未关闭过,例如id=7182,则该服务的表中不存在状态==“关闭” 如何获得计数==0,如下面的示例所示? 我已经突出显示了我需要但无法显示的行的示例 提前多谢了 PS:我一直在玩coalesce,但是运气不好或者现在不知道如何正确使用它在sql查询中获取零计数,sql,count,zero,Sql,Count,Zero,这个话题以前已经讨论过了,但我仍然找不到解决办法。 我正在计算服务的开/关次数。 如果服务从未关闭过,例如id=7182,则该服务的表中不存在状态==“关闭” 如何获得计数==0,如下面的示例所示? 我已经突出显示了我需要但无法显示的行的示例 提前多谢了 PS:我一直在玩coalesce,但是运气不好或者现在不知道如何正确使用它 SELECT id, status, count(*) from history group by id, status order by id, status;
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
如果我理解,现在不显示count=0,您希望在结果中得到它。试一试:
SELECT id, status, count(*) as c
from history
group by id, status
having c >= 0
order by id, status;
一种方法是使用条件求和并将开/关计数作为
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是个坏主意。对不起,不清楚您需要哪个计数。你能再详细说明一下吗
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;