START WITH and CONNECT BY in Oracle SQL

2020-07-14 12:41发布

I have table as below

ACCOUNT

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 

This is the 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)

This is my query

   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;

The main objective of the query is to select data that has a hierarchical relationship, which are PARENT_ACCOUNT_ID & ACCOUNT_ID, however i got a duplicate data returned by the query

Any advice much appreciated. Thanks

标签: sql oracle
2条回答
够拽才男人
2楼-- · 2020-07-14 13:05

Why not simply:

 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

?

查看更多
家丑人穷心不美
3楼-- · 2020-07-14 13:10

You can use pl/sql HOST command to call .exe files.

查看更多
登录 后发表回答