如何使用case语句在MySQL中转动表格?

时间:2013-12-02 04:04:07

标签: mysql pivot-table

我正在尝试使用case语句在MySQL中转动表。这个问题在这里被多次提出,我已经研究了所有这些答案,但我正在寻找一个解决方案:

1.使用案例陈述。不是自我加入,子查询或工会 2.仅使用SQL。不是Excel或shell脚本 3.适用于MySQL。

这是表格:

create table client (
  name varchar(10),
  revenue int(11),
  expense int(11)
);

insert into client (name, revenue, expense) values ("Joe", 100, 200);
insert into client (name, revenue, expense) values ("Bill", 300, 400);
insert into client (name, revenue, expense) values ("Tim", 500, 600);

mysql> select * from client;
+------+---------+---------+
| name | revenue | expense |
+------+---------+---------+
| Joe  |     100 |     200 |
| Bill |     300 |     400 |
| Tim  |     500 |     600 |
+------+---------+---------+

我想把表格转到这个:

+-----+------+-----+
| Joe | Bill | Tim |
| 100 | 300  | 500 |
| 200 | 400  | 600 |
+-----+------+-----+

我该如何做到这一点?

我已经在artfulsoftware dot com和buysql dot com上看过这些解决方案,但这些解决方案对我的桌子不起作用。

1 个答案:

答案 0 :(得分:4)

see fiddle demo here

select 
sum(case when name='Joe' then revenue else 0 end) as JOE,
sum(case when name='Bill' then revenue else 0 end) as Bill,
sum(case when name='Tim' then revenue else 0 end) as TIM

from client

union

select 
sum(case when name='Joe' then expense else 0 end) as JOE,
sum(case when name='Bill' then expense else 0 end) as Bill,
sum(case when name='Tim' then expense else 0 end) as TIM

from client