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`
    

      

  • 相关阅读:
    修改git提交的用户名和密码
    并发编程大师系列之:wait/notify/notifyAll/condition
    并发编程大师系列之:Synchronized的类锁和对象锁
    并发编程大师系列之:线程的定义和中断 interrupt
    SpringBoot项目mysql配置文件密码加密(jasypt)
    Linux下安装nginx实现伪分布
    idea远程debug调试阿里云ECS
    使用docker简单启动springboot项目
    用Navicat连接阿里云ECS服务器上的MySQL数据库
    Linux下安装JDK1.8
  • 原文地址:https://www.cnblogs.com/lihui123/p/14102371.html
Copyright © 2011-2022 走看看