简体   繁体   English

总计总小时数并按小时分组

[英]Sum the total hours and group by hours

I want to group by all the hours between 0 and 40 into one total sum. 我想将0到40之间的所有小时数归为一个总和。 41 - 50 into one total sum and 50+ into another sum. 41-50变成一个总和,而50+变成另一个和。

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

The above query groups by the hours, so i have the results split by hours, like if I have 1, 2.3, 0.5, 35.5, 30 etc. 上面的查询按小时分组,因此我将结果按小时进行拆分,例如如果我有1、2.3、0.5、35.5、30等。

1       403
2.3     4.6
0.5     53
35.5    284
30      1230

But I want something like 403+4.6+53+284+1230 = 1974.6 because they all fall under 40 How can I do it ? 但是我想要类似403+4.6+53+284+1230 = 1974.6因为它们都在40岁以下。我该怎么办?

You can use a conditional aggregation, grouping by a value that builds intervals of hours. 您可以使用条件聚合,并根据建立小时间隔的值进行分组。 By your example, you can have not integer values, so you should use explicit relational operators to have, for example, 40.1 in 40-50 group: 以您的示例为例,您不能具有整数值,因此应使用显式关系运算符在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
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 

GROUP -ing based on CASE 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);
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM