SQL Server计算复杂表达式中的百分比或小数

时间:2017-02-24 03:31:07

标签: sql-server

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_countfail_count都输出整数。

当我第一次尝试创建没有CAST的分数时,我主要使用01几次。我尝试了CAST,但现在它只是0.01.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