行转列容易理解:依次查询所需要的列用union连接
列转化行这个用sum(case when then ) 或者max(case when then ) 结构选取特定行的数据作为列数据!
列转化为行
SELECT user_name ,
MAX(CASE course WHEN'数学' THEN score ELSE 0 END) 数学,
MAX(CASEcourseWHEN'语文'THENscoreELSE0END) 语文,
MAX(CASEcourseWHEN'英语'THENscoreELSE0END) 英语
FROMtest_tb_grade
GROUP BY USER_NAME;
行转化为列
数据表 结果表select user_name,'语文'COURSE , CN_SCORE as SCORE from test_tb_grade2
union
select user_name,'数学'COURSE, MATH_SCORE as SCORE from test_tb_grade2
union
select user_name,'英语'COURSE, EN_SCORE as SCORE from test_tb_grade2
order by user_name,COURSE;
网友评论