在Postgres查询中计算值的实例

SQL新手问题的一点。

如果我有一个符合以下内容的表格:

host    fault                                             fatal groupname
Host A  Data smells iffy                                  n     research
Host B  flanklecrumpet needs a cuddle                     y     production
Host A  RAM loves EWE                                     n     research
Host Z  One of the crossbeams gone askew on the treadle   y     research

..我想获取一些统计信息,..

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     

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

yys19024 回答:在Postgres查询中计算值的实例

使用条件聚合

 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
,

我将使用聚合,但在Postgres中将其表达为:

select groupname,count(distinct host) as hosts,count(*) as num_faults,count(*) filter (where fatal = 'Y') as num_fatal
from t
group by groupname;
本文链接:https://www.f2er.com/3153644.html

大家都在问