oracle列轉行

chengxuyonghu發表於2024-03-12

轉自:https://www.cnblogs.com/Mr_JinRui/archive/2011/05/27/2060109.html

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

表資料如下:

oracle列轉行

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

效果如下:

oracle列轉行

注:sum是求和的意思;比如說裡面記錄裡面有兩條張三,列轉行顯示的結果就會是兩個張三的結果之和。

相關文章