簡單Sql語句統計每年每個月的資料,每個月為資料的每列,簡單SQL練習

qingyezhu發表於2014-09-13

有一張表,資料如下

請寫出結果為以下的SQL語句。

在mysql中建立表

CREATE TABLE `aa` (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '書籍編號',
  `year` varchar(4) NOT NULL DEFAULT '' COMMENT '年',
  `month` varchar(2) NOT NULL DEFAULT '0' COMMENT '月份',
  `mount` double DEFAULT NULL COMMENT '數量',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入資料:

insert into aa(year,month,mount) values(2011,1,1.1),(2011,2,1.2),(2011,3,1.3),(2011,4,1.4);
insert into aa(year,month,mount) values(2012,1,2.1),(2012,2,2.2),(2012,3,2.3),(2012,4,2.4);
insert into aa(year,month,mount) values(2013,1,3.1),(2013,2,3.2),(2013,3,3.3),(2013,4,3.4);
insert into aa(year,month,mount) values(2014,1,4.1),(2014,2,4.2),(2014,3,4.3),(2014,4,4.4);

查詢語句為:

select t2.year,(select t1.mount from aa t1 where t1.year = t2.year and t1.month = 1) m1,
(select t1.mount from aa t1 where t1.year = t2.year and t1.month = 2) m2,
(select t1.mount from aa t1 where t1.year = t2.year and t1.month = 3) m3,
(select t1.mount from aa t1 where t1.year = t2.year and t1.month = 4) m4 from
aa t2 group by t2.year order by t2.year;

完畢。

備註:簡單的實現了一下,若您有更好的,若方便可以共享一下;若有什麼錯誤,請指出,謝謝!

 

相關文章