[英]Calculate correct rate via postgresql
Here'e the table result
's data: 这是表格result
的数据:
question_id is_correct count
64 TRUE 11
66 FALSE 20
77 FALSE 15
77 TRUE 9
I need to calculate the correct rate, which equals (TRUE_COUNT)/(TRUE_COUNT+FALSE_COUNT)
. 我需要计算正确的比率,等于(TRUE_COUNT)/(TRUE_COUNT+FALSE_COUNT)
。 The problem for now is that some questions miss TRUE or FALSE data, I want to fill it with zero in order to do the self join
operation and do the calculation. 现在的问题是某些问题缺少TRUE或FALSE数据,我想用零填充它以便进行self join
运算和计算。 Is there any way to fulfill the requirement or fill with zero? 有什么办法可以满足要求或填零? Great thanks! 万分谢意!
Expected result: 预期结果:
question_id correct_rate
64 1
66 0
77 0.625
No need for a self-join, you can do conditional aggregation: 无需自我加入,您可以进行条件聚合:
select
question_id,
-- to return a percentage
100.0 *
max(case when is_correct = TRUE then count else 0 end) /
sum(count)
-- otherwise needs to add a cast if "count" is an INT
-- max(case when is_correct = TRUE then count else 0 end) /
-- cast(sum(count) as decimal(5,4))
from tab
group by question_id
Conditional aggregation is correct but there are a couple of nuances: 条件聚合是正确的,但有一些细微差别:
SELECT
question_id
,SUM(CASE WHEN is_correct THEN count ELSE 0 END)
/(CASE WHEN SUM(count) < 1 THEN 1 ELSE SUM(count) END)::NUMERIC
FROM
result
GROUP BY
question_id
Make sure you don't end up in a divide by 0 (in case of 0/0), and ensure you cast to a decimal or numeric to get your desired rate. 确保您不会被0除(如果是0/0),并且确保将其转换为小数或数字以得到所需的比率。
Also note your desired result of .625 is not correct for 77 that would be .375 9 true / 24 total 另请注意,您所希望的.625结果与77相对应的结果不正确,即为.375 9 true / 24
You should not need a JOIN
at all. 您完全不需要JOIN
。 Check out below on how to conditionally aggregate your data: 请查看以下有关如何有条件地汇总数据的信息:
SELECT
question_id,
COALESCE(SUM(count) FILTER(WHERE is_correct),0) / SUM(count)::NUMERIC AS rate
FROM
result
GROUP BY
question_id;
-- Older version of PostgreSQL without FILTER:
SELECT
question_id,
COALESCE(SUM(CASE WHEN is_correct THEN count END),0) / SUM(count)::NUMERIC AS rate
FROM
result
GROUP BY
question_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.