Postgresql - 查询列的百分比

时间:2016-02-22 21:24:46

标签: postgresql

我有这个查询,显示案例A和B中出现的主题频率以及案例A的外观百分比。

select subject, 
count(subject) as frequency,
count(case when result='OK' then 1 else null end) as case_a,
count(case when result='NG' then 1 else null end) as case_b,
round(
(
 (count(case when result='OK' then 1 else null end)*100.00)/count(subject)),4)
)
from test
group by subject

我猜测是否有更好的计算百分比的方法,而不必再次应用计数案例。

round(((case_a*100.00) / frequency),4)

试图引用像这样的列^但不起作用。

1 个答案:

答案 0 :(得分:0)

如您所述,您无法像这样引用列别名。解决它的一种方法是将所有计算放在子查询中:

SELECT subject, frequency, case_a, case_b, ROUND(case_a * 100.0 / frequency, 4)
FROM   (SELECT    subject,
                  COUNT(subject) AS frequency,
                  COUNT(CASE WHEN result = 'OK' THEN 1 ELSE NULL END) AS case_a,
                  COUNT(CASE WHEN result = 'NG' THEN 1 ELSE NULL END) AS case_b
         FROM     test
         GROUP BY subject) t

编辑:
作为旁注,如果case表达式中没有条件满足,则返回null,因此您可以使用稍短的表达式。那么效果最终是一样的,所以主要是品味问题:

SELECT subject, frequency, case_a, case_b, ROUND(case_a * 100.0 / frequency, 4)
FROM   (SELECT    subject,
                  COUNT(subject) AS frequency,
                  COUNT(CASE result WHEN 'OK' THEN 1 END) AS case_a,
                  COUNT(CASE result WHEN 'NG' THEN 1 END) AS case_b
         FROM     test
         GROUP BY subject) t