应用 行转列
表结构:TEST_TB_GRADE:
create table TEST_TB_GRADE
(
ID NUMBER(10) not null,
USER_NAME VARCHAR2(20 CHAR),
COURSE VARCHAR2(20 CHAR),
SCORE FLOAT
)
初始数据如下图:
如果需要实现如下的查询效果图:
这就是最常见的行转列,主要原理是利用decode函数、聚集函数(sum),结合group by分组实现的,具体的sql如下:
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