如何把mysql的列修改成行顯示數據簡單實現 創建測試表: 1: DROP TABLE IF EXISTS `test`;<!--CRLF--> 2: CREATE TABLE `test` (<!--CRLF--> 3: `year` int(11) DEFAULT NULL,<!--CRLF-- ...
如何把mysql的列修改成行顯示數據簡單實現
創建測試表:
1: DROP TABLE IF EXISTS `test`;
2: CREATE TABLE `test` (
3: `year` int(11) DEFAULT NULL,
4: `month` int(11) DEFAULT NULL,
5: `amount` double DEFAULT NULL
6: ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入數據:
1: INSERT INTO `test` VALUES ('1991', '1', '1.1');
2: INSERT INTO `test` VALUES ('1991', '2', '1.2');
3: INSERT INTO `test` VALUES ('1991', '3', '1.3');
4: INSERT INTO `test` VALUES ('1991', '4', '1.4');
5: INSERT INTO `test` VALUES ('1992', '1', '2.1');
6: INSERT INTO `test` VALUES ('1992', '2', '2.2');
7: INSERT INTO `test` VALUES ('1992', '3', '2.3');
8: INSERT INTO `test` VALUES ('1992', '4', '2.3');
看到題目要求,仔細想想可以:
利用SUM(IF()) 生成列 + WITH ROLLUP 生成彙總行,並利用 IFNULL將彙總行標題顯示為 Total_num
實現
SQL代碼塊如下:
1: select year,
2: sum(if(month=1,amount,0)) as "M1",
3: sum(if(month=2,amount,0)) as "M2",
4: sum(if(month=3,amount,0)) as "M3",
5: sum(if(month=4,amount,0)) as "M4"
6: from test
7: GROUP by year;
效果如下: