如何通过避免Null值将行数据转换为mysql中的列数据

时间:2016-12-13 10:30:00

标签: mysql

我的表格如下:

 emp_number | leave_status | leave_length_days | leave_type_id |
+------------+--------------+-------------------+---------------+
|        775 |            3 |              1.00 | 001           |
|        775 |            1 |              1.00 | 001           |
|        775 |            1 |              1.00 | 001           |
|        775 |            3 |              1.00 | 001           |
|        775 |            3 |              0.50 | 001           |
|        775 |            1 |              1.00 | 001           |
|        775 |            1 |              1.00 | 001           |
|        775 |            2 |              1.00 | 001           |
|        775 |           11 |              1.00 | 001           |
|        775 |           11 |              1.00 | 001           |
|        775 |            2 |              1.00 | 001           |
|        775 |            2 |              1.00 | 001           |
|        776 |            1 |              1.00 | 001           |
|        776 |            1 |              1.00 | 001           |
|        776 |            4 |              0.00 | 001           |
|        776 |            4 |              0.00 | 001           |
|        776 |            1 |              1.00 | 001           |
|        776 |            1 |              1.00 | 001          

我希望输出像:

+------------+---------------+---------+----------+
| emp_number | leave_type_id | pending | approved |
+------------+---------------+---------+----------+
|        775 | 001           |    4.00 |     8.00 |
|        776 | 001           |    4.00 |     NULL |

我尝试过以下查询:

select emp_number
     , leave_type_id
     , (CASE WHEN leave_status=1 THEN sum(leave_length_days) END) pending
     , (CASE WHEN leave_status=2 THEN sum(leave_length_days) END) approved 
  from em_leave 
 where emp_number in (775,776) 
 group 
    by emp_number
     , leave_status
     , leave_type_id;

但它给我的输出如下:

+------------+---------------+---------+----------+
| emp_number | leave_type_id | pending | approved |
+------------+---------------+---------+----------+
|        775 | 001           |    4.00 |     NULL |
|        775 | 001           |    NULL |     8.00 |
|        775 | 001           |    NULL |     NULL |
|        775 | 001           |    NULL |     NULL |
|        776 | 001           |    4.00 |     NULL |
|        776 | 001           |    NULL |     NULL |
+------------+---------------+---------+----------+

我不想要NULL值。请帮帮我。

1 个答案:

答案 0 :(得分:4)

leave_status移除GROUP BY,将SUM()放在CASE EXPRESSION旁边:

select emp_number
     , leave_type_id
     , SUM(CASE WHEN leave_status=1 THEN leave_length_days ELSE 0 END) pending
     , SUM(CASE WHEN leave_status=2 THEN leave_length_days ELSE 0 END) approved 
  from em_leave 
 where emp_number in (775,776) 
 group by emp_number
        , leave_type_id;

我假设你正在使用MySQL,因为它是唯一允许这个sh * t的DBMS。