• 简单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;

    完毕。

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

  • 相关阅读:
    python json模块出现Invalid control character这个异常的原因
    KMS服务,使用命令激活windows/office
    vscode Python文件头部信息
    MIMIC-III Clinical Database 翻译
    autohotkey 设置
    DeepLearning 写代码常用
    VScode 个人设置
    随机种子设置
    samba配置
    jieba 分词不显示日志
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/3969974.html
Copyright © 2020-2023  润新知