2014-04-29 81 views
0

我有一個表,如:Oracle的SQL:與hiererchical組查詢由

ID || Ent NAME || FUNCTION 
    1 || Dupuis || Signatory 
    1 || Daturt || Decision Maker 
    1 || Nobel  || (Null) 
    2 || Karl  || Decision Maker 
    2 || Titi  || (Null) 
    3 || Cloves || (Null) 
    3 || Cardigan || (Null) 

我想要得到最「重要」的人在預先-established層次(Signatory > Decision Maker > (Null)) 所以期望的結果是:

ID Ent || NAME  || FUNCTION 
     1 || Dupuis || Signatory 
     2 || Karl  || Decision Maker 
     3 || Cardigan || (Null) 

第三,我不在乎人選。

我在甲骨文工作具有非常有限的權利,我能做到這一點SELECT (and this it is s***).

我有一個解決辦法繞過,但它是非常醜陋,我很不滿意:

(SELECT "ID Ent" max (NOM), max (FUNCTION) 
    FROM table 
    WHERE FUNCTION = 'Signatory' GROUP BY "ID Ent") 
UNION 
(SELECT "ID Ent" max (NOM), max (FUNCTION) 
    FROM table 
    WHERE FUNCTION = 'Decision Maker' 
     AND "ID Ent" not in (SELECT "ID Ent" FROM table WHERE FUNCTION = 'Signatory') 
    GROUP BY "ID Ent") 
UNION 
(SELECT "ID Ent" max (NOM), max (FUNCTION) 
    FROM table 
    WHERE FUNCTION = 'Decision Maker' 
     AND "ID Ent" not in (SELECT "ID Ent" in FUNCTION FROM table WHERE ('Signatory', 'Decision Maker')) 
    GROUP BY "ID Ent"); 

你有一個更好的如何做到這一點?

+2

什麼是落後卡爾選擇作爲決策者的邏輯是什麼?爲什麼不Daturt?我試圖瞭解您的要求 – Arnab

+0

Soorry我在第一張表中犯了一個錯誤,Id是公司的ID。我想選擇重要人物。 – user3584811

回答

1

我會接近這個使用分析功能:

select t.Id, t.Name, t.Function 
from (select t.*, 
      row_number() over (partition by id 
           order by (case when function = 'Signatory' then 1 
               when function = 'Decision Maker' then 2 
               else 3 
              end) 
           ) as seqnum 
     from table t 
    ) t 
where seqnum = 1;