计算小数点后四舍五入后的值百分比

时间:2018-07-09 16:03:25

标签: sql select casting decimal rounding

我有一个查询,可以查询列中NULL值的百分比:

SELECT
  Count(*)
FROM
  XYZ_Referrals
WHERE
  referral_source IS NULL
) * 100.0 / (
  Select
    Count(*)
  From
    XYZ_Referrals
) as 'referral source fields that are populated'

但是,我需要将值四舍五入并截断到仅2个小数位。以下查询将四舍五入,但不会截断:

SELECT
  Round
    (
        (
            (
                SELECT
                    Count(*)
                FROM
                    XYZ_Referrals
                WHERE
                    referral_source IS NULL
            )
        * 100.0 / Count(*)
        ),2,2
    )
    as 'referral source fields that are populated'
FROM
  XYZ_Referrals

返回的值为5.600000000000

我尝试过CAST,但没有成功。

SELECT
    (
        Cast
            (
                Round
                    (
                        (
                            (
                                SELECT
                                    Count(*)
                                FROM
                                    XYZ_Referrals
                                WHERE
                                    referral_source IS NULL
                            )
                            * 100.0 / Count(*)
                        )
                    ),2
                AS DECIMAL(3,2)
            )
    )
    as 'referral source fields that are populated'
FROM
  XYZ_Referrals

感谢您的协助。

1 个答案:

答案 0 :(得分:0)

您的路线正确,但DECIMAL中的精度不正确:

SELECT CAST(5.600000000000 AS DECIMAL(10, 2))

这会将数字转换为10位精度,并保留小数点后两位。