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);

 

posted @ 2018-05-24 21:34  草木物语  阅读(5237)  评论(0编辑  收藏  举报