我正在尝试计算'mktcoupons'中重复项的数量并生成重复项的百分比,以便所有百分比的总和等于1。但是,我的所有百分比都是零。有什么建议吗?感谢。
select mktcoupons, count(*) as countof,
count(*)/(select count(*) from X) as percentage
from X
group by mktcoupons
结果如下:
mktcoupons countof percentage
1 2334909 0
2 2725208 0
3 224979 0
4 24987 0
5 2032 0
6 341 0
7 62 0
8 13 0
9 5 0
10 1 0
答案 0 :(得分:0)
SQL Server执行整数除法。您可以显式将值转换为带小数点的数字。我经常乘以1.0:
select mktcoupons, count(*) as countof,
count(*)/(select 1.0*count(*) from X) as percentage
from X
group by mktcoupons;
也就是说,此查询不需要子查询。您可以改为使用窗口函数:
select mktcoupons, count(*) as countof,
count(*)/sum(1.0 * count(*)) over () as percentage
from X
group by mktcoupons;
如果您有一个复杂的WHERE
子句或JOIN
,则必须在子查询中复制这一点,这一点特别有用。