【问题标题】:Sum the total hours and group by hours总小时数和按小时分组
【发布时间】:2016-04-27 15:11:12
【问题描述】:

我想将 0 到 40 之间的所有时间分组为一个总和。 41 - 50 为一个总和,50+ 为另一个总和。

select hours,
       sum(hours)
from   employee
where  hours between 0 and 40
group by hours;

上述查询按小时分组,因此我将结果按小时划分,例如我有 1、2.3、0.5、35.5、30 等。

1       403
2.3     4.6
0.5     53
35.5    284
30      1230

但我想要类似的东西 403+4.6+53+284+1230 = 1974.6 因为他们都在 40 岁以下 我该怎么做?

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您可以使用条件聚合,按构建小时间隔的值进行分组。 通过您的示例,您可以没有整数值,因此您应该使用显式关系运算符来拥有,例如 40-50 组中的 40.1:

    select sum(hours),
           case
              when hours <= 40 then '0-40'
              when hours > 40 and hours <= 50 then '41-50'
              when hours > 50 then '50-...'
             end
    from employee
    group by case
              when hours <= 40 then '0-40'
              when hours > 40 and hours <= 50 then '41-50'
              when hours > 50 then '50-...'
             end
    

    【讨论】:

      【解决方案2】:
      select sum(case when hours between 0 and 40 then hours else 0 end) hours_1,
             sum(case when hours between 41 and 50 then hours else 0 end) hours_41,
             sum(case when hours > 50 then hours else 0 end) hours_51
      from employee 
      

      【讨论】:

        【解决方案3】:

        GROUP-ing 基于CASE

        select (case when hours between 0 and 40
                      then '0 - 40'
                      when hours between 41 and 50
                      then '41 - 50'
                      else
                           '50+'
                  end) as hours_range,
                sum(hours) 
        from employee
        group by (case when hours between 0 and 40
                      then '0 - 40'
                      when hours between 41 and 50
                      then '41 - 50'
                      else
                           '50+'
                  end);
        

        【讨论】:

        • 如何将它们作为行而不是列,我是否必须与另一个选择进行联合?
        【解决方案4】:
        select '1 to 40',sum(hours)
        
        from   employee
        where  hours between 0 and 40
        
        union all
        
          select '41 to 50',sum(hours)
        
        from   employee
        where  hours between 41 and 50
        
        union all
        
          select '50+',sum(hours)
        
        from   employee
        where  hours>50
        

        【讨论】:

        • 哪个版本的性能更好,union all 或像其他答案中一样执行case 语句
        猜你喜欢
        • 2018-08-27
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多