【问题标题】:How to pivot a table in MySQL using case statements?如何使用 case 语句在 MySQL 中旋转表?
【发布时间】:2013-12-02 04:04:07
【问题描述】:

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

【问题讨论】:

  • 你不能。不是根据你的限制。
  • 杰夫,哪个限制阻止了解决方案?
  • 您需要使用联合,因为您在两个不同的列(收入和费用)上进行聚合。
  • 我并不是说你不能完成你需要的,我只是不明白你为什么要给自己设置这些限制。
  • 好的,谢谢你的提示,请告诉我如何使用案例陈述和联合来完成?

标签: mysql pivot-table


【解决方案1】:

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

【讨论】:

  • 为什么是-1?它给出了预期的结果?
  • Vijaykumar,是的,你是对的,它给出了预期的结果,我不知道谁给出了 -1。我刚刚 +1。
  • 那是因为当你添加更多数据时它变得低效,但这是一种方法
  • @VijaykumarHadalgi 不幸的是,没有避免硬编码名称以防万一
  • @VijaykumarHadalgi 在 mysql 中,是的。一些数据库(例如(MSSQL)具有对数据透视的本机支持,它允许在不知道(在这种情况下)名称的情况下在结果中创建列。不幸的是,Mysql 没有这个。您可能支持带有存储的动态名称构建和执行动态 SQL 的过程,但它会很丑陋。这个查询可以稍微改进一下,但至少它可以在所有数据库上工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 2015-05-18
  • 1970-01-01
  • 2021-04-02
相关资源
最近更新 更多