多行查詢結果合併sys_connect_by_path

Oracle同行合併分組linux

表結構爲:
create table test(
bookid char(3) not null,
author varchar2(10) not null
);
 
insert into test values('001','jack');
insert into test values('001','tom');
insert into test values('002','wang');
insert into test values('002','zhang');
insert into test values('002','li');
 
commit;
 
select * from test;
顯示結果爲:
BOO AUTHOR
-----------------
001 jack
001 tom
002 wang
002 zhang
002 li
 
咱們想獲得的結果爲:
BOO AUTHOR
-----------------------------
001 jack&&tom
002 wang&&zhang&&li
 
SQL文爲:
select bookid,substr(max(sys_connect_by_path(author,'&&')),3) authoride

from
(select bookid,author,id,lag(id) over(partition by bookid order by id) pid函數

--(最後一列或者爲)lead(id) over(partition by bookid order by id desc) pid
from (select bookid,author,rownum id from test))網站

start with pid is null
connect by prior id=pid
group by bookid;
 
詳細解釋:
sys_connect_by_path(column,'')//column爲列名,''中間加要添加的字符
這個函數自己不是用來給咱們作結果集鏈接的(合併行),而是用來構造樹路徑的,因此須要和connect by一塊兒使用。spa

本篇文章來源於 Linux公社網站(www.linuxidc.com)  原文連接:http://www.linuxidc.com/Linux/2012-02/55492.htmhtm

相關文章
相關標籤/搜索