MySQL DML操作--------实现pivot行转列功能最佳实战
1. 背景
* 由于MySQL 不支持类型Oracle与SQL Server的pivot功能进行行列转换。
2. 表与数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
mysql> select * from t_temp;
+ ---------+-----------+------------+
| year | season | orderCount |
+ ---------+-----------+------------+
| 2010年 | 一季度 | 100 | | 2010年 | 二季度 | 200 | | 2010年 | 三季度 | 300 | | 2010年 | 四季度 | 400 | | 2011年 | 一季度 | 150 | | 2011年 | 二季度 | 300 | | 2011年 | 三季度 | 450 | | 2011年 | 四季度 | 600 | + ---------+-----------+------------+
8 rows in set (0.00 sec)
|
3. 通过子查询与case when判断实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
mysql> select year , sum (orderCount1) '第一季度' ,
-> sum (orderCount2) '第二季度' ,
-> sum (orderCount3) '第三季度' ,
-> sum (orderCount4) '第四季度' -> from -> (
-> select year ,
-> case when season = '一季度' then -> orderCount
-> end orderCount1,
-> case when season = '二季度' then -> orderCount
-> end orderCount2,
-> case when season = '三季度' then -> orderCount
-> end orderCount3,
-> case when season = '四季度' then -> orderCount
-> end orderCount4
-> from t_temp
-> ) t
-> group by year ;
+ ---------+--------------+--------------+--------------+--------------+
| year | 第一季度 | 第二季度 | 第三季度 | 第四季度 |
+ ---------+--------------+--------------+--------------+--------------+
| 2010年 | 100 | 200 | 300 | 400 | | 2011年 | 150 | 300 | 450 | 600 | + ---------+--------------+--------------+--------------+--------------+
2 rows in set (0.00 sec)
|
4. 通过IF聚合函数实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
mysql> SELECT year ,
-> SUM (IF(season = '一季度' , orderCount, null )) AS '第一季度' ,
-> SUM (IF(season = '二季度' , orderCount, null )) AS '第二季度' ,
-> SUM (IF(season = '三季度' , orderCount, null )) AS '第三季度' ,
-> SUM (IF(season = '四季度' , orderCount, null )) AS '第四季度'
-> FROM t_temp
-> GROUP BY year ;
+ ---------+--------------+--------------+--------------+--------------+
| year | 第一季度 | 第二季度 | 第三季度 | 第四季度 |
+ ---------+--------------+--------------+--------------+--------------+
| 2010年 | 100 | 200 | 300 | 400 | | 2011年 | 150 | 300 | 450 | 600 | + ---------+--------------+--------------+--------------+--------------+
2 rows in set (0.00 sec)
|
5. 总结
以需求驱动技术,技术本身没有优略之分,只有业务之分。
本文转自asd1123509133 51CTO博客,原文链接:http://blog.51cto.com/lisea/1949764,如需转载请自行联系原作者