orcale 中查詢多行 後合併到一行顯示

l23456789o發表於2018-11-06

 

select listagg(某列,',')within group(order by 某列主鍵 desc)from 某表;

 

 

詳細:

1、有一表,表結構如下:

2、想把這張表的資訊合併一下,即以ID 和CODE 為聯合主鍵,分組合並,把CODENAE裡資訊合併到一行裡;此處用到多行合併到一行,合併結果如下:

 

步驟:

1.建表:

create table  testlisstagg ( id int,code int,codename varchar2(20));

2、插入資料 

insert into testlisstagg (ID, CODE, CODENAME)values (1,1, 'A');
insert into testlisstagg (ID, CODE, CODENAME)values (1,2, 'B');
insert into testlisstagg (ID, CODE, CODENAME)values (1,2, 'C');
insert into testlisstagg (ID, CODE, CODENAME)values (2,1, 'A');
insert into testlisstagg (ID, CODE, CODENAME)values (2,1, 'B');
insert into testlisstagg (ID, CODE, CODENAME)values (3,2, 'C');
insert into testlisstagg (ID, CODE, CODENAME)values (3,2, 'A');

3、合併使用的程式碼:

(1)

select distinct a.id,
       a.code,
      (select listagg(codename, ',') within group(order by code desc)
          from testlisstagg b where b.id=a.id and b.code=a.code) 合併後
  from testlisstagg a order by 1,2;

(2) 簡便的寫法:

select b.id,b.code, listagg(codename, ',') within group(order by code desc)
          from testlisstagg b group by b.id,b.code order by  b.id,b.code

 

 

 

相關文章