生成两个查询之间的百分比指标

时间:2020-05-14 21:21:21

标签: sql database postgresql group-by count

如何在不同条件的同一张表的两个查询之间生成百分比指标?

示例:

_________________________________________
            |        |         |
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

1 个答案:

答案 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

在此结果集中,metrics01之间的值,代表'ON'记录的比率。您可以通过将其乘以100轻松地将其转换为百分比。