gpt4 book ai didi

mysql - 如何使用 case 语句在 MySQL 中转换表?

转载 作者:行者123 更新时间:2023-11-29 04:45:07 24 4
gpt4 key购买 nike

我正在尝试使用 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 上看到了解决方案,但这些解决方案不适用于我的表。

最佳答案

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

关于mysql - 如何使用 case 语句在 MySQL 中转换表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com