【发布时间】:2012-07-19 13:38:43
【问题描述】:
我有一个联系人表,其中包括每个联系人在附近居住的时间长度:
ID First_Name Last_Name Neighborhood_Time
1 John Smith 1-2 years
2 Mary Jones 2-5 years
3 Dennis White 2-5 years
4 Martha Olson 5+ years
5 Jeff Black 5+ years
6 Jean Rogers 2-5 years
我想显示时间百分比,结果如下:
One_to_2_Years Two_to_5_Years 5+_Years
16 50 33
这是我正在使用的:
select
sum(case when Neighborhoods_time ='1-2 years' then 1 else 0 end)*100/(select count(*) from contact) as One_to_2_Years,
sum(case when Neighborhoods_time ='2-5 years' then 1 else 0 end)*100/(select count(*) from contact) as Two_to_6_Years,
sum(case when Neighborhoods_time ='5+years' then 1 else 0 end)*100/(select count(*) from contact) as Six_to_10_Years
from dbo.contact
这是我的结果:
One_to_2_Years Two_to_5_Years 5+_Years
0 0 16
16 33 0
0 16 16
我看到每列下的数字都是正确的,但我在对它们求和时遇到了问题。
我错过了什么?
谢谢。
【问题讨论】:
-
您不需要在每列中使用
/(select count(*) from contact),只需使用/ count(*) AS,因为您已经从contact中选择了 -
谢谢 Nicola,你是对的。
-
@GarethD 感谢您的帮助。