最常见的 行 转 列,主要原理是利用decode函数、聚集函数(sum),结合group by分组实现的:
select t.user_name,
sum(decode(t.course, '语文', score,null)) as CHINESE,
sum(decode(t.course, '数学', score,null)) as MATH,
sum(decode(t.course, '英语', score,null)) as ENGLISH
from test_tb_grade t
group by t.user_name
order by t.user_name
>>>>>>>>>>>>>>>>
最常见的 列 转 行,主要原理是利用SQL里面的union/union all:
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
>>>>>>>>>>>>>>>>>>>>>>>