2011-02-03 94 views
1

是否有可能爲表中的許多行生成「連接方式」並將它們總和。 我有一個表SQL連接多行

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 
+0

很難理解你想要什麼。你真的認爲那裏有一排p1 p3嗎?你想要總結一些東西嗎? – Randy 2011-02-03 18:44:12

回答

5

更新

看到你更新後,你只需要刪除下手。

末更新

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和組是很容易