行列轉換的幾種形式
行列轉換包含如下幾種形式:行轉列、列轉行、多列轉換成字符串、多行轉換成字符串、字符串轉換成多列、字符串轉換成多行
一、Oracle行列轉置
1、行轉列
(1)創建表格、插入測試數據
create table student( id number, name varchar2(20), course varchar2(20), score number )
插入測試數據,如下:
(2)方法一:使用wm_concat()函數
select id, name, wm_concat(score) scores from student group by id, name;
結果集如下:
(3)方法二:使用decode()函數
select id,name,sum(decode(course,'Chinese',score,null)) "Chinese", sum(decode(course,'Math',score,null)) "Math", sum(decode(course,'English',score,null)) "English" from student group by id,name
結果集如下:
(4)方法三:使用case表達式
select id,name,sum(case when course='Chinese' then score end) "Chinese", sum(case when course='Math' then score end) "Math", sum(case when course='English' then score end) "English" from student group by id,name
結果集如下:
2、列轉行
(1)建表
使用上面的查詢結果:
create table scores as select id,name,sum(case when course='Chinese' then score end) "Chinese", sum(case when course='Math' then score end) "Math", sum(case when course='English' then score end) "English" from student group by id,name order by i
得到表及記錄如下:
(2)方法一:合並查詢union
select id,name,'Chinese' as course from scores union select id,name,'Math' as course from scores union select id,name,'English' as course from scores
結果集如下: