Oracle 行列轉換函式pivot使用簡介

2021-10-06 18:33:12 字數 2891 閱讀 7245

語法示例:

select 

* from table_name

pivot( max(column_name01) --行轉列後的列的值value,聚合函式是必須要有的

for column_name02 in(value_1,value_2,value_3) --需要行轉列的列及其對應列的屬性1/2/3

);

建表語句:

-- create table

create table t_student_score

( id varchar2(20) not null,

student_no varchar2(20),

student_name varchar2(100),

student_course varchar2(100),

student_score number(5,2)

)tablespace users;

-- add comments to the table

comment on table t_student_score

is '學生資訊表';

-- add comments to the columns

comment on column t_student_score.id

is '主鍵id';

comment on column t_student_score.student_no

is '學號';

comment on column t_student_score.student_name

is '姓名';

comment on column t_student_score.student_course

is '課程';

comment on column t_student_score.student_score

is '學分';

sql語句:

select 

student_no,

max(case when student_course = '語文' then student_score end) 語文,

max(case when student_course = '數學' then student_score end) 數學,

max(case when student_course = '英語' then student_score end) 英語,

max(case when student_course = '物理' then student_score end) 物理,

sum(student_score) total

from t_student_score

group by student_no;

資料庫截圖:

sql語句:

select 

student_no,

max(decode(student_course, '語文', student_score)) 語文,

max(decode(student_course, '數學', student_score)) 數學,

max(decode(student_course, '英語', student_score)) 英語,

max(decode(student_course, '物理', student_score)) 物理,

sum(student_score) total

from t_student_score

group by student_no;

資料庫截圖:

sql語句:

-- 列轉成行 pivot 【注意查詢列】

select

*from (

select t.student_no, t.student_course, t.student_score from t_student_score t

) mpivot ( max(student_score) for student_course in ('語文', '數學', '英語', '物理') );

資料庫截圖:

sql語句:

-- 列轉成行 pivot 【未篩選查詢列】

select

*from t_student_score

pivot ( max(student_score) for student_course in ('語文', '數學', '英語', '物理') );

資料庫截圖:

Oracle行列轉換

1.列轉行 create table t col row id int,c1 varchar2 10 c2 varchar2 10 c3 varchar2 10 insert into t col row values 1,v11 v21 v31 insert into t col row valu...

Oracle行列轉換

行轉列 select count over cnt,rn,str from select rownum rn,substr a.str,instr a.str,1,a.n 1,instr a.str,1,a.n 1 instr a.str,1,a.n 1 str from select a,b,c,...

oracle 行列轉換

q 如何實現行列轉換 a 1 固定列數的行列轉換 如student subject grade student1 語文 80 student1 數學 70 student1 英語 60 student2 語文 90 student2 數學 80 student2 英語 100 轉換為 語文 數學 英...