按小时计算总小时数和小组数

时间:2016-04-27 15:11:12

标签: sql oracle

我希望将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岁 我该怎么办?

4 个答案:

答案 0 :(得分:2)

您可以使用条件聚合,按照构建小时间隔的值进行分组。 根据您的示例,您可以没有整数值,因此您应该使用显式关系运算符,例如,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

答案 1 :(得分:1)

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 

答案 2 :(得分:1)

GROUP - 基于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);

答案 3 :(得分:0)

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