Oracle 11g 列轉行listagg
在Oracle 11g之前列轉行有些麻煩,11g之後,非常簡單。現在有功能的業務是,有一張test的表記錄的是單據的審批資訊,id為審批資訊的主鍵,sheet_id為外鍵,是單據的id,remark為審批的內容,在前端的列表頁面上,要看到這個單據所有的審批資訊,要顯示在一個格子裡面。
SQL> drop table test purge;
SQL> create table test
(
id number(10),
sheet_id number(10),
remark varchar2(50)
);
SQL> insert into test values(1,100,'審批意見1');
SQL> insert into test values(2,100,'審批意見2');
SQL> insert into test values(3,100,'審批意見3');
SQL> insert into test values(4,200,'同意1');
SQL> insert into test values(5,200,'同意2');
SQL> insert into test values(6,200,'同意3');
SQL> insert into test values(7,300,'回退1');
SQL> insert into test values(8,300,'回退2');
SQL> commit;
SQL> col C_REMARK format a40;
SQL> select sheet_id,listagg(remark,',') within GROUP (order by id) as c_remark
from test
group by sheet_id;
SHEET_ID C_REMARK
---------- ----------------------------------------
100 審批意見1,審批意見2,審批意見3
200 同意1,同意2,同意3
300 回退1,回退2
還有一種寫法:
SQL> select sheet_id, listagg(remark, ',') within
GROUP(
order by id) over(partition by sheet_id) c_remark
from test;
SHEET_ID C_REMARK
---------- ----------------------------------------
100 審批意見1,審批意見2,審批意見3
100 審批意見1,審批意見2,審批意見3
100 審批意見1,審批意見2,審批意見3
200 同意1,同意2,同意3
200 同意1,同意2,同意3
200 同意1,同意2,同意3
300 回退1,回退2
300 回退1,回退2
SQL> select distinct sheet_id, listagg(remark, ',') within
GROUP(
order by id) over(partition by sheet_id) c_remark
from test;
SHEET_ID C_REMARK
---------- ----------------------------------------
200 同意1,同意2,同意3
100 審批意見1,審批意見2,審批意見3
300 回退1,回退2
Oracle 11g 新聚集合函式listagg實現列轉行