【问题标题】:Sum(case results not right总和(案例结果不正确
【发布时间】: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 感谢您的帮助。

标签: sql sum case


【解决方案1】:

按 Neighborhoods_time 添加组

【讨论】:

    【解决方案2】:

    你的查询的基础可以像

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-02
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多