我试图计算出我的数据中男性占多大比例,女性占多大比例。
我有以下代码:
select
SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END) / COUNT(Gender) as perc_male,
SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END) / COUNT (Gender) as perc_female
From [my_table]
但是运行此命令时,我得到0%。有人可以看到我在这里做错什么吗?
谢谢
答案 0 :(得分:0)
我认为值小于1,这就是为什么您得到0 尝试如下
select
SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END) / COUNT(Gender)*1.00
as perc_male,
SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END) / COUNT (Gender)*1.00
as perc_female
From [my_table]
或在float数据类型中使用显式强制转换
答案 1 :(得分:0)
只需使用:
select
SUM(CASE WHEN Gender = 'M' THEN 1.0 ELSE 0.0 END) / COUNT(Gender)
as perc_male,
SUM(CASE WHEN Gender = 'F' THEN 1.0 ELSE 0.0 END) / COUNT (Gender)
as perc_female
From [my_table]
您正在使用整数。在处理整数时,SQL总是尝试返回整数,在这种情况下-ot向下舍入为0。
答案 2 :(得分:0)
使用其中一个值的显式转换来获得所需的精度,例如
select
SUM(CASE WHEN Gender = 'M' THEN 1 ELSE 0 END) / cast(COUNT(Gender) as decimal(5,3)) as perc_male,
SUM(CASE WHEN Gender = 'F' THEN 1 ELSE 0 END) / cast(COUNT(Gender) as decimal(5,3)) as perc_female
From [my_table]
答案 3 :(得分:0)
问题是整数除法。我认为最简单的方法是使用AVG()
:
SELECT AVG(CASE WHEN Gender = 'M' THEN 1.0 ELSE 0 END) as perc_male,
AVG(CASE WHEN Gender = 'F' THEN 1.0 ELSE 0 END) as perc_female
FROM [my_table]