MySQL:基于另一列的值的一列的SUM

时间:2019-05-31 03:20:20

标签: mysql sql

我想有一个基于另一列的值是this / that的列的总和。这是我的表结构

id  leave_hours leave_type overtime_hours employee_id
1     7.6          1           0               3
2      5           2           0               3
3      0           0           2.3             3

我已经有了这个查询,但是我需要有一列,仅在休假类型为1且休假类型为2时求和

SELECT employee_id, SUM(overtime_hours) AS ot_hrs, SUM(leave_hours if leave_type == 1) AS  
       leave_1, SUM(leave_hours if leave_type == 2) AS leave_2
FROM table
GROUP BY employee_id

结果应为:

employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5

感谢您的输入。

2 个答案:

答案 0 :(得分:3)

您需要使用条件聚合来分别汇总不同的leave_hours

SELECT employee_id, 
       SUM(overtime_hours) AS ot, 
       SUM(CASE WHEN leave_type = 1 THEN leave_hours ELSE 0 END) AS leave_1, 
       SUM(CASE WHEN leave_type = 2 THEN leave_hours ELSE 0 END) AS leave_2
FROM `table`
GROUP BY employee_id

输出:

employee_id ot      leave_1     leave_2
3           2.3     7.6         5

Demo on dbfiddle

请注意,如果您使用浮点数来存储小时数,则可能需要ROUND结果。

答案 1 :(得分:0)

您可以在遇到以下情况时使用max()

SELECT employee_id, 
       max(overtime_hours) AS ot, 
       max(CASE WHEN leave_type = 1 THEN leave_hours  END) AS leave_1, 
       max(CASE WHEN leave_type = 2 THEN leave_hours END) AS leave_2
FROM  table_name
GROUP BY employee_id

输出

employee_id     ot     leave_1       leave_2
3              2.3  7.599999904632568   5