总和(案例结果不对

时间:2012-07-19 13:38:43

标签: sql sum case

我有一个联系表,其中包括每个联系人在附近居住的时间长度:

 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

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

我错过了什么?

感谢。

2 个答案:

答案 0 :(得分:0)

按Neighborhoods_time添加分组

答案 1 :(得分: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