SQL连接多行

时间:2011-02-03 18:32:25

标签: sql oracle

是否可以为表中的许多行生成“connect by”并将它们全部加起来。 我有一张桌子

person boss
---------------    
person1 NULL
person2 person1
person3 person2

我想得到表

boss is_boss_of
---------------
person1 person2
person1 person3
person2 person3

我想通过表达式为桌面人物老板中的每个人建立连接? 有没有办法实现呢?

说到总和我想到这样的事情

SELECT CONNECT_BY_ROOT person as boss, person as is_boss_of
            FROM table1
            START WITH boss = person1
            CONNECT BY PRIOR Empno = Mgr;
Union
SELECT CONNECT_BY_ROOT person as boss, person as is_boss_of
            FROM table1
            START WITH boss = person2
            CONNECT BY PRIOR Empno = Mgr;
Union
...
and so on

1 个答案:

答案 0 :(得分:5)

<强>更新

看到您的更新后,您只需要放弃START WITH。

结束更新

CONNECT_BY_ROOT正是您要找的

本声明

SELECT distinct RootBoss, Person FROM (
with employee  as 
(
  Select 1 person , null boss from Dual
  UNION Select 2 , 1 from dual
  UNION Select 3 , 2 from dual
)
SELECT CONNECT_BY_ROOT boss RootBoss, person
FROM employee connect_by

  connect by prior person = boss
  ORDER BY person

  ) t
WHERE ROOTBOSS is not null
ORDER BY
RootBoss, Person

输出

ROOTBOSS               PERSON                 
---------------------- ---------------------- 
1                      2                      
1                      3                      
2                      3        

添加SUMS和GROUPS非常简单