SQL COUNT()在分割时返回0

时间:2014-04-14 19:56:42

标签: sql

我正在努力创造一个非常快速的&简单的客户报告。我确信我有一些语法错误,因为%的结果总是为0.这是SQL和示例结果集:

DECLARE @TotalCount INT
SELECT @TotalCount = (SELECT COUNT(1) FROM TABLE WHERE OrderCompleteFlag = 1)
PRINT @TotalCount

SELECT '21 - 25', COUNT(1) AS 'COUNT', (COUNT(1) / @TotalCount) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 21 and 35 AND OrderCompleteFlag = 1
UNION
SELECT '26 - 30', COUNT(1) AS 'COUNT', (COUNT(1) / @TotalCount) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 26 and 30 AND OrderCompleteFlag = 1

结果:

11175

21 - 25 7631    0
26 - 30 3544    0

非常感谢任何帮助。 THX!

丹尼斯

*** UPDATE ***

The quick fix (on SQL SERVER) was to just declare @TotalCount as 
DECIMAL or NUMERIC.  thanks to everyone that helped solve with input! :)

3 个答案:

答案 0 :(得分:2)

您应该将您要分割的数字转换为小数。

TRY:

DECLARE @TotalCount INT
SELECT @TotalCount = (SELECT COUNT(1) FROM TABLE WHERE OrderCompleteFlag = 1)
PRINT @TotalCount

SELECT '21 - 25', COUNT(1) AS 'COUNT', (COUNT(1) / Cast(@TotalCount As Decimal)) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 21 and 35 AND OrderCompleteFlag = 1
UNION
SELECT '26 - 30', COUNT(1) AS 'COUNT', (COUNT(1) / Cast(@TotalCount As Decimal)) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 26 and 30 AND OrderCompleteFlag = 1

答案 1 :(得分:0)

你需要将除数转换为十进制,否则你除以整数:

DECLARE @TotalCount INT
SELECT @TotalCount = (SELECT COUNT(1) FROM TABLE WHERE OrderCompleteFlag = 1)
PRINT @TotalCount

SELECT '21 - 25', COUNT(1) AS 'COUNT', (COUNT(1) / CAST(@TotalCount AS FLOAT)) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 21 and 35 AND OrderCompleteFlag = 1
UNION
SELECT '26 - 30', COUNT(1) AS 'COUNT', (COUNT(1) / CAST(@TotalCount AS FLOAT)) FROM TABLE WHERE DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 26 and 30 AND OrderCompleteFlag = 1

答案 2 :(得分:0)

在编写查询时,只需将@TotalCount声明为浮点或十进制类型:

declare @TotalCount float;

其余部分保持不变。

但是,您可以大大简化查询。以下基本上可以满足您的需求,但使用"其他"生成额外的行。年龄组:

SELECT (CASE WHEN DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 21 and 25 THEN '21 - 25'
             WHEN DATEDIFF(yy, DateOfBirth, GETDATE()) BETWEEN 26 and 30 THEN '26 - 30' 
        END) as AgeGroup,
       COUNT(*) AS "Count",
       COUNT(*) / SUM(COUNT(*)*1.0) OVER () as Ratio
FROM TABLE
WHERE OrderCompleteFlag = 1;

您可以使用此子句解决该问题:

HAVING MIN(DATEDIFF(yy, DateOfBirth, GETDATE())) BETWEEN 21 and 30