日期:2014-05-16 浏览次数:20386 次
create table treetest (col1 varchar2(4),col2 varchar2(4)); insert into treetest values ('1','你'); insert into treetest values ('1','好'); insert into treetest values ('1','哦'); insert into treetest values ('1','好'); insert into treetest values ('2','天'); insert into treetest values ('2','上'); insert into treetest values ('2','地'); insert into treetest values ('2','下'); insert into treetest values ('3','美'); insert into treetest values ('3','丽'); insert into treetest values ('3','一'); insert into treetest values ('3','天'); //查出行号,便于排序 select rownum num,t3.col1,t3.col2 from treetest t3; //forConnectBy区分不同树,connect by 处用,forStartWith在同树中的顺序,start with 处用 select t1.col1 c1,to_number(t1.col1)+row_number() over (order by t1.num) forConnectBy, row_number() over(partition by t1.col1 order by t1.col1) forStartWith,t1.col2 c3 from (select rownum num,t3.col1,t3.col2 from treetest t3) t1; //sys_connect_by_path(expr,'分隔符'),start with 从这里开始找树,connect by 连接成一棵树的条件 select replace(max(sys_connect_by_path(t2.c3,'/')),'/','') from (select t1.col1 c1,to_number(t1.col1)+row_number() over (order by t1.num) forConnectBy, row_number() over(partition by t1.col1 order by t1.col1) forStartWith,t1.col2 c3 from (select rownum num,t3.col1,t3.col2 from treetest t3) t1) t2 start with t2.forStartWith = 1 connect by prior t2.forConnectBy = t2.forConnectBy - 1 group by t2.c1 order by t2.c1;