目錄結構如下:
行轉列列轉行
[一]、行轉列
1.1、初始測試資料
表結構:test_tb_grade
sql**
create table test_tb_grade
( id number(10) not null,
user_name varchar2(20 char),
course varchar2(20 char),
score float
) 初始資料如下圖:
1.2、 如果需要實現如下的查詢效果圖:
這就是最常見的行轉列,主要原理是利用decode函式、聚集函式(sum),結合group by分組實現的,具體的sql如下:
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
1.3、延伸
如果要實現對各門功課的不同分數段進行統計,效果圖如下:
具體的實現sql如下:
sql**
select t2.score_gp,
sum(decode(t2.course, '語文', countnum,null)) as chinese,
sum(decode(t2.course, '數學', countnum,null)) as math,
sum(decode(t2.course, '英語', countnum,null)) as english
from (
select t.course,
case when t.score <60 then '00-60'
when t.score >=60 and t.score <80 then '60-80'
when t.score >=80 then '80-100' end as score_gp,
count(t.score) as countnum
from test_tb_grade t
group by t.course,
case when t.score <60 then '00-60'
when t.score >=60 and t.score <80 then '60-80'
when t.score >=80 then '80-100' end
order by t.course ) t2
group by t2.score_gp
order by t2.score_gp
[二]、列轉行
1.1、初始測試資料
表結構:test_tb_grade2
sql**
create table test_tb_grade2
( id number(10) not null,
user_name varchar2(20 char),
cn_score float,
math_score float,
en_score float
) 初始資料如下圖:
1.2、 如果需要實現如下的查詢效果圖:
這就是最常見的列轉行,主要原理是利用sql裡面的union,具體的sql語句如下:
sql**
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
也可以利用【 insert all into ... select 】來實現,首先需要先建乙個表test_tb_grade3:
sql**
create table test_tb_grade3
( user_name varchar2(20 char),
course varchar2(20 char),
score float
)
再執行下面的sql:
sql**
insert all
into test_tb_grade3(user_name,course,score) values(user_name, '語文', cn_score)
into test_tb_grade3(user_name,course,score) values(user_name, '數學', math_score)
into test_tb_grade3(user_name,course,score) values(user_name, '英語', en_score)
select user_name, cn_score, math_score, en_score from test_tb_grade2;
commit;
別忘記commit操作,然後再查詢test_tb_grade3,發現表中的資料就是列轉成行了。
Oracle行列轉換小結
oracle行列轉換小結 目錄結構如下 行轉列列轉行 一 行轉列 1.1 初始測試資料 表結構 test tb grade sql create table test tb grade id number 10 not null,user name varchar2 20 char course v...
Oracle行列轉換小結
oracle行列轉換小結 目錄結構如下 行轉列列轉行 一 行轉列 1.1 初始測試資料 表結構 test tb grade sql create table test tb grade id number 10 not null,user name varchar2 20 char course v...
Oracle行列轉換小結
目錄結構如下 一 行轉列 1.1 初始測試資料 表結構 test tb grade sql create table test tb grade id number 10 not null,user name varchar2 20 char course varchar2 20 char scor...