MySQL查询根据部门显示工资

时间:2014-03-01 04:20:38

标签: mysql sql

我遇到了一个特殊的问题。我几乎尝试过所有我认识的事情。 该表包含以下详细信息:

+--------+---------+--------+----------+
| emp_id | dept_no | salary | emp_name |
+--------+---------+--------+----------+
|      1 | c1      |  12300 | Rajesh   |
|      2 | c2      |  45123 | Arvind   |
|      3 | c3      |  12345 | Ravi     |
+--------+---------+--------+----------+

预期的输出是这样的:

+---------+--------+--------+--------+
| Dept_no | DeptC1 | Deptc2 | DeptC3 |
+---------+--------+--------+--------+
| c1      |  12300 |      0 |      0 |
| c2      |      0 |  45123 |      0 |
| c3      |      0 |      0 |  12345 |
+---------+--------+--------+--------+

我真的遇到了这个问题,并且不知道如何解决这个问题。我试图用左外连接来解决这个问题,但是无法做到。

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT Dept_no,
       if(Dept_no='C1',salary,0) as Dept_noC1,
       if(Dept_no='C2',salary,0) as Dept_noC2,
       if(Dept_no='C3',salary,0) as Dept_noC3
From Emp
Group by Dept_no;

Fiddle Demo

输出:

+---------+--------+--------+--------+
| Dept_no | DeptC1 | Deptc2 | DeptC3 |
+---------+--------+--------+--------+
| c1      |  12300 |      0 |      0 |
| c2      |      0 |  45123 |      0 |
| c3      |      0 |      0 |  12345 |
+---------+--------+--------+--------+