2015-11-05 60 views
1

我有一個表看起來像這樣PL/SQL ORDER BY WHERE A = B

ID NUMBER, 
NAME VARCHAR(2), 
Sub_ID 

Sub_ID可以爲空。 數據可能如下所示。

ID  NAME    SUB_ID 
1  A  
2  B     1 
3  C     1 
4  D     3 
5  E     2 
6  F     1 
7  G     6 

我希望它有點像這個

 ID  NAME     SUB_ID 
      1  A  
      2  B     1 
      5  E     2 
      3  C     1 
      4  D     3 
      6  F     1 
      7  G     6 

我試圖這樣

ORDER BY ID ASC, Sub_ID ASC 

排序呢但這並沒有工作,這就是爲什麼我在尋找一個方法來像這樣排序。

ORDER BY WHERE(ID ASC=Sub_ID) ASC 
+1

您沒有任何數據,其中'ID = SUB_ID'所以我不明白如何改變你的排序。 –

+0

請您詳細說明*排序標準*?只需說明*這樣排序是什麼意思*?根據提供的樣本,「SUB_ID」永遠不等於「ID」 –

回答

2

聽起來像connect byorder siblings by可能是你追求的:

with your_table as (select 1 id, 'A' name, null sub_id from dual union all 
        select 2 id, 'B' name, 1 sub_id from dual union all 
        select 3 id, 'C' name, 1 sub_id from dual union all 
        select 4 id, 'D' name, 3 sub_id from dual union all 
        select 5 id, 'E' name, 2 sub_id from dual union all 
        select 6 id, 'F' name, 1 sub_id from dual union all 
        select 7 id, 'G' name, 6 sub_id from dual) 
select * 
from your_table 
connect by prior id = sub_id 
start with sub_id is null 
order siblings by sub_id; 

     ID NAME  SUB_ID 
---------- ---- ---------- 
     1 A    
     2 B    1 
     5 E    2 
     3 C    1 
     4 D    3 
     6 F    1 
     7 G    6 
相關問題