我正在尝试使用 case 语句在 MySQL 中透视表。这个问题在这里被问过很多次,我已经研究了所有这些答案,但我正在寻找一种解决方案:
1. 使用 case 语句。不是自联接、子查询或联合。
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 |
+------+---------+---------+
Run Code Online (Sandbox Code Playgroud)
我想将表格转为:
+-----+------+-----+
| Joe | Bill | Tim |
| 100 | 300 | 500 |
| 200 | 400 | 600 |
+-----+------+-----+
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我已经在 artfulsoftware dot com 和 buysql dot com 上看到了解决方案,但这些解决方案对我的表不起作用。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1690 次 |
| 最近记录: |