wm_concat函式的排序問題

newknight發表於2013-11-28

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;
 
         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          5
       
測試wm_concat後的順序:
測試1:
SQL> select m,wm_concat(n) from t group by m;
 
         M WM_CONCAT(N)
———- ——————————————————————————–
         1 11,0,1,10
         2 17,2,7,12
         3 15,3,5,13
         5 16,6
        
可見wm_concat後的順序並沒有按大->小,或小->大的順序。

測試2:
–參考網上一些解決思路
SQL> select m,wm_concat(n)
  2    from (select n,m from t order by m,n )
  3   group by m;
 
         M WM_CONCAT(N)
———- ——————————————————————————–
         1 0,11,10,1
         2 2,17,12,7
         3 3,15,13,5
         5 6,16

可見順序問題還是沒有解決

最終解決思路:
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

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10009036/viewspace-1061450/,如需轉載,請註明出處,否則將追究法律責任。

相關文章