CREATE TABLE `gas` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `oil` VARCHAR(100) NULL DEFAULT NULL, `district` VARCHAR(100) NULL DEFAULT NULL, `price` DOUBLE NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11;
2、测试数据如下,select * from gas;
| id | oil | district | price || 9 | #97 | 罗湖 | 33 |
3、行列转换:
select ifnull(oil,'total') as oil, sum(if(district='宝安',price,0)) AS BA, sum(if(district='福田',price,0)) AS FT, sum(if(district='罗湖',price,0)) AS LH, SUM(price) AS TOTAL from gas group by oil with rollup ;
| oil | BA | FT | LH | TOTAL |
| #0 | 11 | 12 | 13 | 36 |
| #93 | 21 | 22 | 23 | 66 |
| #97 | 31 | 32 | 33 | 96 |
| total | 63 | 66 | 69 | 198 |
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/rongku/article/details/46851443