简单Sql语句统计每年每个月的数据,每个月为数据的每列,简单SQL练习

时间:2023-03-08 21:23:50

有一张表,数据如下

简单Sql语句统计每年每个月的数据,每个月为数据的每列,简单SQL练习

请写出结果为以下的SQL语句。

简单Sql语句统计每年每个月的数据,每个月为数据的每列,简单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;

完毕。

备注:简单的实现了一下,若您有更好的,若方便可以共享一下;若有什么错误,请指出,谢谢!