SELECT
person,
(CAST( /* I tried with and without CAST */
COUNT(`something`) / /* success count is numerator */
(COUNT(`something`) +
SUM(case when `something` is null then 1 else 0 end)) AS DECIMAL(3,1))
/* sum of success + failure counts is denominator. */
) success_ratio,
SUM(case when `something` is null then 1 else 0 end) fail_count,
COUNT(`something`) success_count
FROM
`table`
GROUP BY
person
ORDER BY
person
在我的输出中,success_count
和fail_count
都输出整数。
当我第一次尝试创建没有CAST
的分数时,我主要使用0
,1
几次。我尝试了CAST
,但现在它只是0.0
和1.1
。
我做错了什么?
答案 0 :(得分:1)
我认为你的问题是你正在施放整数除法的值而不是单个部分
您可以使用子查询使事情更容易阅读,并且在case语句中使用1.0或0.0可以强制字段为浮点
SELECT person,
success_count / ( success_count + fail_count) success_rate,
fail_count, success_count
FROM (
SELECT person,
(
SUM(case when `something` is null then 1.0 else 0.0 end) fail_count,
SUM(case when `something` is null then 1.0 else 0.0 end) success_count
FROM `table`
GROUP BY person
) x
ORDER BY person