創(chuàng)建測(cè)試表:
1
2
3
4
5
6
|
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( ` year ` int (11) DEFAULT NULL , ` month ` int (11) DEFAULT NULL , `amount` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
插入數(shù)據(jù):
1
2
3
4
5
6
7
8
|
INSERT INTO `test` VALUES ( '1991' , '1' , '1.1' ); INSERT INTO `test` VALUES ( '1991' , '2' , '1.2' ); INSERT INTO `test` VALUES ( '1991' , '3' , '1.3' ); INSERT INTO `test` VALUES ( '1991' , '4' , '1.4' ); INSERT INTO `test` VALUES ( '1992' , '1' , '2.1' ); INSERT INTO `test` VALUES ( '1992' , '2' , '2.2' ); INSERT INTO `test` VALUES ( '1992' , '3' , '2.3' ); INSERT INTO `test` VALUES ( '1992' , '4' , '2.3' ); |
看到題目要求,仔細(xì)想想可以:
利用SUM(IF()) 生成列 + WITH ROLLUP 生成匯總行,并利用 IFNULL將匯總行標(biāo)題顯示為 Total_num
實(shí)現(xiàn)
SQL代碼塊如下:
1
2
3
4
5
6
7
|
select year , sum (if( month =1,amount,0)) as "M1" , sum (if( month =2,amount,0)) as "M2" , sum (if( month =3,amount,0)) as "M3" , sum (if( month =4,amount,0)) as "M4" from test GROUP by year ; |
效果如下:
以上所述是小編給大家介紹的Mysql的列修改成行并顯示數(shù)據(jù)的簡(jiǎn)單實(shí)現(xiàn),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/HRuinger/archive/2016/10/23/5989839.html