在MySql中生成伪列

时间:2017-09-20 14:04:33

标签: mysql pivot-table

我有多个工作和多个部门的表,我想以这样的方式处理数据,它将提供部门明智和工作明智的薪资信息。我怎样才能做到这一点?只能使用select和case或类似的吗?

输入表:

+------+-----------+--------+--------+--------------+
| id   | name      | salary | deptno | job          |
+------+-----------+--------+--------+--------------+
|    1 | Lucas     |  20000 |      1 | Founder      |
|    2 | Gabriello |  18300 |      1 | Cofounder    |
|    3 | Teodoor   |  15000 |      2 | Sales        | 
|    4 | Ronna     |  12600 |      3 | Marketing    |
|    5 | Dixie     |   6800 |      3 | Janitor      |
|    6 | Kelsey    |   6400 |      2 | Janitor      |
|    7 | Tatiania  |  15200 |      2 | Sales        |
|    8 | Goldia    |  12400 |      3 | Marketing    |
+------+-----------+--------+--------+--------------+

输出表:

deptno  Founder    Cofounder      Sales       Marketing   Janitor
------------------------------------------------------------------
  1      20000       18300          0             0         0
  2        0           0       15000+15200        0        6400
  3        0           0            0        12600+12400   6800

1 个答案:

答案 0 :(得分:4)

select deptno, 
       sum(case when job = 'Founder' then salary else 0 end) as Founder,
       sum(case when job = 'Cofounder' then salary else 0 end) as Cofounder,
       sum(case when job = 'Sales' then salary else 0 end) as Sales,
       sum(case when job = 'Marketing' then salary else 0 end) as Marketing,
       sum(case when job = 'Janitor' then salary else 0 end) as Janitor
from your_table
group by deptno