zoukankan      html  css  js  c++  java
  • mysql 横变竖 竖变横

    竖变横

    创表  

    CREATE TABLE `score` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) DEFAULT NULL,
      `project` varchar(50) DEFAULT NULL,
      `score` varchar(3) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;
    

    添加数据

    INSERT INTO `score` VALUES ('1', '小明', '语文', '90');
    INSERT INTO `score` VALUES ('2', '小明', '数学', '70');
    INSERT INTO `score` VALUES ('3', '小明', '英语', '60');
    INSERT INTO `score` VALUES ('4', '小红', '语文', '97');
    INSERT INTO `score` VALUES ('5', '小红', '数学', '60');
    INSERT INTO `score` VALUES ('6', '小红', '英语', '80');
    INSERT INTO `score` VALUES ('7', '小亮', '语文', '70');
    INSERT INTO `score` VALUES ('8', '小亮', '数学', '80');
    INSERT INTO `score` VALUES ('9', '小亮', '英语', '60');
    

     竖变横

    select
    	`name` "姓名",
    	max(case project when '语文' THEN score ELSE 0 END) "语文",
    	max(case project when '数学' THEN score ELSE 0 END) "数学",
    	max(case project WHEN '英语' THEN score ELSE 0 END) "英语"
    from score group by `name`
    

      

    横变竖

    创表

    CREATE TABLE `student` (
      `id` varchar(32) NOT NULL,
      `姓名` varchar(50) NOT NULL,
      `语文` int(11) DEFAULT NULL,
      `数学` int(11) DEFAULT NULL,
      `物理` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    添加数据

    INSERT INTO `student1` VALUES ('0001', '小张', '93', '84', '99');
    INSERT INTO `student1` VALUES ('0002', '小马', '86', '92', '90');

    横变竖

    select * from 
    (select
    	`姓名` 'name','语文'as'project',`语文` 'score'
    from student group by `name`
    UNION ALL
    select
    	`姓名` 'name','数学'as'project',`数学` 'score'
    from student
    UNION ALL
    select
    	`姓名` 'name','物理'as'project',`物理` 'score'
    from student
    )t order by `name`
    

      

  • 相关阅读:
    Python字符串的定义与常用操作
    Python中yield返回生成器的详细方法
    python中把列表中的字符串转成整型的3种方法
    python基础教程:修改Python列表中元素的几种方法
    极致性能设计——开篇
    MySQL设计与实现
    Java平台标准版工具参考
    为什么for循环中的a=a++,a总是0
    JVM 分析工具快速查询手册
    从现代计算机低层看待性能和并发
  • 原文地址:https://www.cnblogs.com/lihui123/p/14102371.html
Copyright © 2011-2022 走看看