mysql从表中用case,如何使用case语句在MySQL中透视表?

I am trying to pivot a table in MySQL using case statements. This question has been asked many times here, and I have studied all of those answers, but I am looking for a solution that:

1. Uses case statements. Not self joins, subqueries, or unions.

2. Uses just SQL. Not Excel or shell scripts.

3. Works on MySQL.

Here is the table:

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 |

+------+---------+---------+

I would like to pivot the table to this:

+-----+------+-----+

| Joe | Bill | Tim |

| 100 | 300 | 500 |

| 200 | 400 | 600 |

+-----+------+-----+

How can I accomplish this?

I have already seen the solutions at artfulsoftware dot com and buysql dot com, but those solutions are not working for my table.

解决方案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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值