简体   繁体   中英

MySQL: SUM of a column based on a value of another column

I want to have a sum of a column that is based if the value of another column is this/that. Here's my table structure

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

I have this query already but I need to have a column that will only sum if leave type is 1 and if the leave type is 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

Result should be:

employee_id  ot_hrs leave_1  leave_2
    3          2.3    7.6       5

Thanks for your inputs.

You need to use conditional aggregation to sum the different leave_hours separately:

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

Output:

employee_id ot      leave_1     leave_2
3           2.3     7.6         5

Demo on dbfiddle

Note that if you use floating point numbers to store the hours, you may need to ROUND the results.

you can use max() with case when

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

output

employee_id     ot     leave_1       leave_2
3              2.3  7.599999904632568   5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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