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

我看到每列下的数字都是正确的,我在求和它们时遇到了问题。

我错过了什么?

谢谢。

4

2 回答 2

0

按 Neighborhoods_time 添加组

于 2012-07-19T13:41:52.237 回答
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
于 2012-07-19T14:23:50.377 回答