• mysql 行转列 列转行


    行转列

     --> 

    SELECT user_name ,
      MAX(CASE course WHEN '数学' THEN score END ) 数学,
      MAX(CASE course WHEN '语文' THEN score END ) 语文,
      MAX(CASE course WHEN '英语' THEN score END ) 英语
    FROM test_tb_grade
    GROUP BY USER_NAME;

    在 mybatis 中实现 动态行转列

    <select id="list" resultType="java.util.HashMap">
      SELECT user_name ,
        <if test="courses != null">
            <foreach collection="courses " item="item" separator=",">
            MAX(CASE course WHEN #{item} THEN score END ) "${item}"
            </foreach>
        </if>
      FROM test_tb_grade
      GROUP BY USER_NAME;
    </select>

    列转行

    -->

    select user_name, '语文' as COURSE , CN_SCORE as SCORE from test_tb_grade2
    union select user_name, '数学' as COURSE, MATH_SCORE as SCORE from test_tb_grade2
    union select user_name, '英语' as COURSE, EN_SCORE as SCORE from test_tb_grade2
    order by user_name,COURSE;

    表数据:

    CREATE TABLE `TEST_TB_GRADE` (
        `ID` INT (10) NOT NULL AUTO_INCREMENT,
        `USER_NAME` VARCHAR (20) DEFAULT NULL,
        `COURSE` VARCHAR (20) DEFAULT NULL,
        `SCORE` FLOAT DEFAULT '0',
        PRIMARY KEY (`ID`)
    ) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;
    
    INSERT INTO TEST_TB_GRADE (USER_NAME, COURSE, SCORE)
    VALUES
        ("张三", "数学", 34),
        ("张三", "语文", 58),
        ("张三", "英语", 58),
        ("李四", "数学", 45),
        ("李四", "语文", 87),
        ("李四", "英语", 45),
        ("王五", "数学", 76),
        ("王五", "语文", 34),
        ("王五", "英语", 89);
    
    CREATE TABLE `TEST_TB_GRADE2` (
        `ID` INT (10) NOT NULL AUTO_INCREMENT,
        `USER_NAME` VARCHAR (20) DEFAULT NULL,
        `CN_SCORE` FLOAT DEFAULT NULL,
        `MATH_SCORE` FLOAT DEFAULT NULL,
        `EN_SCORE` FLOAT DEFAULT '0',
        PRIMARY KEY (`ID`)
    ) ENGINE = INNODB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8;
    
    INSERT INTO TEST_TB_GRADE2 (
        USER_NAME,
        CN_SCORE,
        MATH_SCORE,
        EN_SCORE
    )
    VALUES
        ("张三", 34, 58, 58),
        ("李四", 45, 87, 45),
        ("王五", 76, 34, 89);
  • 相关阅读:
    一看就懂的Mybatis框架入门笔记
    一文了解有趣的位运算(&、|、^、~、>>、<<)
    探究如何永久更改Maven的Dynamic Web Project版本及pom.xml默认配置
    编译流程之仿真
    数字逻辑基础2
    1. FPGA内部的逻辑资源
    c++ 入门之深入探讨拷贝函数和内存分配
    c++入门之浅拷贝和深拷贝
    c++入门之详细探讨类的一些行为
    c++入门之类与内存
  • 原文地址:https://www.cnblogs.com/ooo0/p/9085224.html
Copyright © 2020-2023  润新知