我目前正在做一个SUM CASE来锻炼一个百分比,但整个字符串返回零或一个(整数),但我不知道为什么。我已经编写了部分SQL来分解它并确保底层数据是正确的,但是当我添加最后一部分来执行它失败的百分比时。我错过了什么吗?
SELECT
SUPPLIERCODE,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)) AS ACCEPTABLE,
COUNT(ID) AS TOTALSUBMITTED,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)/COUNT(ID))
FROM SUPPLIERDATA
GROUP BY SUPPLIERCODE
例如,这里返回了一些数据:
SUPPLIERCODE ACCEPTABLE TOTALSUBMITTED Column1
HBFDE2 1018 1045 0
DTETY1 4 4 1
SWYTR2 579 736 0
VFTEQ3 2104 2438 0
我知道我可以离开其他列并使用excel计算,但我宁愿不...任何帮助都会很受欢迎。感谢
答案 0 :(得分:2)
SELECT
SUPPLIERCODE,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)) AS ACCEPTABLE,
COUNT(ID) AS TOTALSUBMITTED,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)*1.0/COUNT(ID))
FROM SUPPLIERDATA
GROUP BY SUPPLIERCODE
您需要将结果转换为float。通过乘以1.0
可以轻松完成答案 1 :(得分:1)
这是因为SQL Server将您的值视为INT
以进行除法。
请尝试以下操作,您将看到答案0
:
PRINT 1018 / 1045
为了让您的操作正常运行,您需要将值转换为FLOAT
s,如下所示:
PRINT CAST(1018 AS FLOAT) / 1045
这将按预期产生答案0.974163
。
对您的声明进行简单更改以将演员阵容引入FLOAT
将对您的问题进行排序:
SELECT
SUPPLIERCODE,
(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END)) AS ACCEPTABLE,
COUNT(ID) AS TOTALSUBMITTED,
(CAST(SUM(CASE WHEN ISNULL(DATESUBMITTED,0) - ISNULL(FAILDATE,0) <15 THEN 1 ELSE 0 END) AS FLOAT) / COUNT(ID))
FROM SUPPLIERDATA
GROUP BY SUPPLIERCODE
答案 2 :(得分:0)
您需要做的就是通过为数据库引擎提供一个提示来避免整数除法。
在SQL Server中,您将使用:
SELECT
SUPPLIERCODE,
(SUM(CASE WHEN ISNULL(DATESUBMITTED, 0) - ISNULL(FAILDATE, 0) < 15 THEN 1 ELSE 0 END)) AS ACCEPTABLE,
COUNT(ID) AS TOTALSUBMITTED,
(SUM(CASE WHEN ISNULL(DATESUBMITTED, 0) - ISNULL(FAILDATE, 0) < 15 THEN 1 ELSE 0 END) / (COUNT(ID) * 1.0))
FROM
SUPPLIERDATA
GROUP BY
SUPPLIERCODE