ITPub博客

首页 > 数据库 > 数据库开发技术 > mysql列转行

mysql列转行

原创 数据库开发技术 作者:orclwujian 时间:2016-04-21 11:24:00 0 删除 编辑

测试数据:
mysql>create table sale(mo
nth int(6),product varchar(32),amount decimal(20,2)
mysql> insert into sale values(201502,'apple',3500.00);
Query OK, 1 row affected (0.01 sec)
mysql> insert into sale values(201502,'banana',3000.00);
Query OK, 1 row affected (0.01 sec)
mysql> insert into sale values(201502,'pear',1000.00);
Query OK, 1 row affected (0.01 sec)
mysql> insert into sale values(201502,'orange',1000.00);
Query OK, 1 row affected (0.01 sec)
mysql> commit;
Query OK, 0 rows affected (0.00 sec)


mysql> select * from sale;
+--------+---------+---------+
| month  | product | amount   |
+--------+---------+---------+
| 201502 | apple   | 3500.00 |
| 201502 | banana  | 3000.00 |
| 201502 | pear    | 1000.00 |
| 201502 | orange  | 1000.00 |
+--------+---------+---------+
4 rows in set (0.00 sec)
现在前端展现要求需要以product为行的数据,具体实现如下:
SELECT 
month,
max(case when product='apple' then mount ELSE 0 END) apple,
max(case when product='banana' then mount ELSE 0 END) banana,
max(case when product='pear' then mount ELSE 0 END) pear,
max(case when product='orange' then mount ELSE 0 END) orange
FROM sale GROUP BY month;

+--------+---------+---------+---------+---------+
| month  | apple   | banana  | pear    | orange  |
+--------+---------+---------+---------+---------+
| 201502 | 3500.00 | 3000.00 | 1000.00 | 1000.00 |
+--------+---------+---------+---------+---------+
1 row in set (0.00 sec)
注:GROUP BY之后一定要用max函数,不然会出现banana,pear,orange会出现空
原因:
SELECT 
month,
case when product='apple' then mount ELSE 0 END apple,
case when product='banana' then mount ELSE 0 END banana,
case when product='pear' then mount ELSE 0 END pear,
case when product='orange' then mount ELSE 0 END orange
FROM sale 结果是:
+--------+---------+---------+---------+---------+
| month  | apple   | banana  | pear    | orange  |
+--------+---------+---------+---------+---------+
| 201502 | 3500.00 |       0 |       0 |       0 |
| 201502 |       0 | 3000.00 |       0 |       0 |
| 201502 |       0 |       0 | 1000.00 |       0 |
| 201502 |       0 |       0 |       0 | 1000.00 |
+--------+---------+---------+---------+---------+
4 rows in set (0.00 sec)
group by后只会取第一条记录,除了apple其他字段都是0,所以要加个max,把每个字段的最大值取出来。




来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29989552/viewspace-2085266/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: mysql processlist
请登录后发表评论 登录
全部评论

注册时间:2014-10-29

  • 博文量
    95
  • 访问量
    322684