wm_concat在行轉列的時候很是有用,但在行轉列的過程當中的排序問題經常難以控制。測試
可見下面例子:
準備測試表:
drop table t;
create table t (n number,m number);
insert into t values(1,1);
insert into t values(5,3);
insert into t values(3,3);
insert into t values(6,5);
insert into t values(7,2);
insert into t values(2,2);
insert into t values(0,1);
insert into t values(11,1);
insert into t values(15,3);
insert into t values(13,3);
insert into t values(16,5);
insert into t values(17,2);
insert into t values(12,2);
insert into t values(10,1);
commit;排序
SQL> select * from t order by 2,1;it
N M
———- ———-
0 1
1 1
10 1
11 1
2 2
7 2
12 2
17 2
3 3
5 3
13 3
15 3
6 5
16 5io
測試wm_concat後的順序:
測試1:
SQL> select m,wm_concat(n) from t group by m;table
M WM_CONCAT(N)
———- ——————————————————————————–
1 11,0,1,10
2 17,2,7,12
3 15,3,5,13
5 16,6select
可見wm_concat後的順序並無按大->小,或小->大的順序。tab
測試2:
–參考網上一些解決思路
SQL> select m,wm_concat(n)
2 from (select n,m from t order by m,n )
3 group by m;co
M WM_CONCAT(N)
———- ——————————————————————————–
1 0,11,10,1
2 2,17,12,7
3 3,15,13,5
5 6,16ab
可見順序問題仍是沒有解決commit
最終解決思路:
SQL> select m, max(r)
2 from (select m, wm_concat(n) over (partition by m order by n) r from t)
3 group by m ;
M MAX(R) ———- ——————————————————————————– 1 0,1,10,11 2 2,7,12,17 3 3,5,13,15 5 6,16