zoukankan      html  css  js  c++  java
  • 简单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;

    完毕。

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

  • 相关阅读:
    虚拟机docker开启服务,本地无法进行访问
    make编译提示:make cc Command not found 解决办法
    yum -y install git 无法安装...提示There are no enabled repos.
    linux 安装mysql
    linux 配置环境变量
    HTML5第三天 无序有序列表、相对绝对路径
    JavaScript第一天
    HTML第二天
    mysql流程控制语句
    mysql存储过程和函数
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/3969974.html
Copyright © 2011-2022 走看看