mysql-行转列
采用case函数进行行转列:
1、第一步
mysql> select * from a;
+----+--------+
| id | name |
+----+--------+
| 1 | 张三 |
| 2 | 李四 |
| 3 | 王五 |
+----+--------+
3 rows in set (0.00 sec)
2、第二步
mysql> select
-> case name when '张三' then id end as '张三',
-> case name when '李四' then id end as '李四',
-> case name when '王五' then id end as '王五'
-> from a;
+--------+--------+--------+
| 张三 | 李四 | 王五 |
+--------+--------+--------+
| 1 | NULL | NULL |
| NULL | 2 | NULL |
| NULL | NULL | 3 |
+--------+--------+--------+
3 rows in set (0.00 sec)
3、第三步
sum() 或max()函数
mysql> select
-> sum(case name when '张三' then id end) as '张三',
-> sum(case name when '李四' then id end )as '李四',
-> sum(case name when '王五' then id end) as '王五'
-> from a;
+--------+--------+--------+
| 张三 | 李四 | 王五 |
+--------+--------+--------+
| 1 | 2 | 3 |
+--------+--------+--------+
1 row in set (0.00 sec)