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