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