如何在不同条件的同一张表的两个查询之间生成百分比指标?
示例:
_________________________________________
| | |
environment | online | offline | metrics
____________|________|_________|_________
web 3 1 75%
docker 2 1 50%
查询1:
Select environment, count(available) from tb_infra where available = 'ON' group by environment order by count desc
查询2:
Select environment, count(available) from tb_infra where available = 'OFF' group by environment order by count desc
答案 0 :(得分:2)
您可以进行条件聚合。 Postgres支持的用于聚合函数的标准filter
子句对此很方便:
select
environment,
count(*) filter(where available = 'ON') online,
count(*) filter(where available = 'OFF') offline,
avg((available = 'ON')::int) metrics
from tb_infra
group by environment
在此结果集中,metrics
是0
和1
之间的值,代表'ON'
记录的比率。您可以通过将其乘以100
轻松地将其转换为百分比。