首页 > 解决方案 > 在 postgres 查询中计算值的实例

问题描述

有点 SQL 新手问题..

如果我有一个表格,如下所示:

主机故障致命组名
主机 A 数据闻起来很可疑
主持人 B Flanklecrumpet 需要一个拥抱 y 制作
主持人 A RAM 喜欢 EWE n 研究
主持人 Z 踏板上的一根横梁歪斜 y 研究

..我想得到一些统计数据,我可以..

select count(distinct host) as hosts, count(host) as faults, group from tablename group by groupname

..这给了我每个组名的故障数和受影响的主机。

hosts    faults    groupname
2        3         research
1        1         production     

我可以在同一个查询中显示致命条目的数量吗?

标签: sqlpostgresql

解决方案


使用条件聚合

 select count(distinct host) as hosts,
 count(host) as faults,sum(case when fatal='y' then 1 else 0 end) as numberofenty,
 groupname from tablename group by groupname

推荐阅读