2012-02-13 89 views
3

我有表如下START WITH和甲骨文CONNECT BY SQL

賬戶

CUSTOMER_ID PAYING_ACCOUNT_ID PARENT_ACCOUNT_ID  ACCOUNT_ID COMPANY_ID 
24669   24669    24669     24669  0 
24671   24671    24669     24671  0 
24670   24670    24669     24670  0 
3385217  3385217    24670     3385217  0 
158   158     158     158   0 
159   159     158     159   0 
160   160     159     160   0 
161   161     160     161   0 
162   162     160     162   0 
180   180     180     180   0 

這是DDL

CREATE TABLE "SYSTEM"."ACCOUNT" 
("CUSTOMER_ID"  NUMBER(20,0) NOT NULL ENABLE, 
"PAYING_ACCOUNT_ID" NUMBER(20,0), 
"PARENT_ACCOUNT_ID" NUMBER(20,0), 
"ACCOUNT_ID"  NUMBER, 
"COMPANY_ID"  NUMBER) 

這是我的查詢

select lpad(' ', 2*level) || A.ACCOUNT_ID AS LEVEL_LABEL, 
      LEVEL, 
      A.* 
     from ACCOUNT A 
start with PARENT_ACCOUNT_ID IN 
         (select PARENT_ACCOUNT_ID 
          from ACCOUNT 
         where ACCOUNT_ID IN 
             (select PARENT_ACCOUNT_ID 
              from ACCOUNT 
              where parent_account_id != account_id) 
              and ACCOUNT_ID = PARENT_ACCOUNT_ID) 
    CONNECT BY NOCYCLE PRIOR A.ACCOUNT_ID = A.PARENT_ACCOUNT_ID; 

查詢的主要目的是選擇具有層次關係的數據,即PARENT_ACCOUNT_ID & ACCOUNT_ID,但是我得到了查詢返回的重複數據。

任何建議非常感謝。由於

+1

parent_account_id和account_id如何在同一時間(最內在的查詢)不同和相等?這可能不是您的原始查詢,因爲它應該產生完全爲0的結果,因此根本沒有重複。 – Benoit 2012-02-13 09:25:06

回答

6

爲什麼不乾脆:

SELECT level, * FROM accounts 
START WITH parent_account_id = account_id 
CONNECT BY PRIOR account_id = parent_account_id 
     AND account_id <> parent_account_id 

+0

感謝您的建議。 – user871695 2012-02-13 09:23:56

+0

@ user871695這個答案能工作嗎? – cctan 2012-02-13 09:27:25

+0

是的,它工作:) – user871695 2012-02-14 03:19:18

0

您可以使用pl/sql HOST命令來調用.exe文件。