Oracle 行轉列兩種方法
1.新建一個名為TEST表
2.向TEST表中添加數據
INSERT INTO TEST(STUDENT,COURSE,SCORE)
select ‘張三‘,‘語文‘,78 from dual union
select ‘張三‘,‘數學‘,87 from dual union
select ‘張三‘,‘英語‘,82 from dual union
select ‘張三‘,‘物理‘,90 from dual union
select ‘李四‘,‘語文‘,65 from dual union
select ‘李四‘,‘數學‘,77 from dual union
select ‘李四‘,‘英語‘,65 from dual union
select ‘李四‘,‘物理‘,85 from dual
表數據如下:
3.列轉行
方法··1:
select
Student,
sum(decode(Course, ‘數學‘, Score)) 數學,
sum(decode(Course, ‘物理‘, Score)) 物理,
sum(decode(Course, ‘英語‘, Score)) 英語,
sum(decode(Course, ‘語文‘, Score)) 語文
from
TEST
group by Student
方法··2:
select
Student,
sum(case Course when ‘數學‘ then Score else null end) 數學,
sum(case Course when ‘物理‘ then Score else null end) 物理,
sum(case Course when ‘英語‘ then Score else null end) 英語,
sum(case Course when ‘語文‘ then Score else null end) 語文
from
TEST
group by Student
效果如下:
註:sum是求和的意思;比如說裏面記錄裏面有兩條張三,列轉行顯示的結果就會是兩個張三的結果之和。
來自:https://blog.csdn.net/rlhua/article/details/24668755
Oracle 行轉列兩種方法