2016-04-27 101 views
1

我想將0到40之間的所有小時數組合成一個總數。將一個總數和一個總和中的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 我該怎麼辦?

回答

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
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 
1

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); 
+0

怎樣才能讓他們爲行,而不是專欄,我必須做一個工會所有與另一個選擇? – user525146

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 
+0

哪個版本執行得更好,如同其他答案一樣,'union all'或者做'case'語句 – user525146