2012-07-19 46 views
0

我有一个通讯录,包括时间每个联系人住在附近的长度:总和(情况会导致不正确的

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 

我看到每列下的数字是正确的,我有一个问题总结他们。

我错过了什么?

谢谢。

+1

删除组通过。 – 2012-07-19 13:42:33

+0

你不需要在每一列使用'/(从联系人中选择count(*))',因为你已经从联系人中选择了'/ count(*)AS'' – GarethD 2012-07-19 13:48:25

+0

感谢Nicola,你正确。 – Stan 2012-07-19 13:53:13

回答

0

添加组通过Neighborhoods_time

0

您的查询的基础上,可以产生像

select 
    Neighborhood_Time, 
    100*COUNT(*)/(Select COUNT(*) from contact) as percentvalue 
from 
    contact 
group by 
    Neighborhood_Time 

如果你想水平布置,那么你应该使用一个支点

select 
* 
from 
(
select 
    Neighborhood_Time, 
    100*COUNT(*)/(Select COUNT(*) from contact) as percentvalue 
from 
    contact 
group by 
    Neighborhood_Time 
) src 
PIVOT 
(SUM(percentvalue) for Neighborhood_Time in ([1-2 years],[2-5 years],[5+ years])) as pt 
相关问题