oracle行列轉換

2021-06-18 10:11:18 字數 1694 閱讀 5712

1、多行轉換單列字串

比如:

需要轉換成:

1    b,z,x

2    c,x

寫法1:

select t.rank ,max(substr(sys_connect_by_path(t.name, ','), 2))

from (select rank, name, row_number() over(partition by rank order by rowid ) rn

from temptest2) t

start with rn = 1

connect by rn = prior rn + 1

and rank = prior rank

group by t.rank;

sys_connect_by_path

會組織一條路徑

,比如,a,b,c  

通過substr

再擷取會有

aa,b

a,b,c

max即得到結果

寫法2:

select t.rank, wmsys.wm_concat(t.name) time from temptest2 t  group by t.rank;
2、單列字串轉換成多行即上面得到的結果再轉換回去

寫法1:

with t as ( 

select 1 id1,',tt,aa,bb' c1 from dual union

select 2 id1,',abc,xyz' c1 from dual

)select  distinct  id1,regexp_substr(c1,'[^,]+',1,level) from t connect by level < =length(c1)-length(replace(c1,',',''));

寫法2:

with t as ( 

select 1 id1,',tt,aa,bb' c1 from dual union

select 2 id1,',abc,xyz' c1 from dual

)select distinct id1,substr(c1||',',instr(c1||',',',',1,level)+1,instr(c1||',',',',1,level+1) - instr(c1||',',',',1,level)- 1 ),

level

from t connect by level < =length(c1)-length(replace(c1,',',''));

通過connect by拆分成多行,拆成多少行由逗號決定。之後再通過substr結合level擷取

3、多行轉換成多列

通過max(case when... )或sum(case when...)

4、多列轉換成多行

通過union all

union all

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 轉換為 語文 數學 英...