簡體   English   中英

如何編寫一個復雜的 sql 或 post sql 查詢來返回輸入的所有數據關系?

[英]How do I write a complex sql or post sql query that will return all data relationships for an input?

例如,一個帳戶 (A1) 有兩個擁有該帳戶的客戶 (C1, C2)。 C1 也是另一個客戶 (C3) 的單獨帳戶 (A2) 的所有者。 C2 也是另外兩個帳戶(A3、A4)的所有者,另一個客戶 (C4) 是 A4 的共同所有者。

我正在尋找一個(循環?)查詢,它將識別數據輸入 A1 的所有關系(例如 A2-4、C1-4)。

| Account | Customer |
|---------|----------|
| A1      | C1       |
| A1      | C2       |
| A2      | C1       |
| A2      | C3       |
| A3      | C2       |
| A4      | C2       |
| A4      | C4       |
| A5      | C5       |
| A6      | C6       |

嘗試:從 Account.Customer 中選擇客戶,帳戶,其中帳戶 = A1; for each(account) [查找屬於每個帳戶的所有客戶(該帳戶內的客戶)[查找屬於該客戶的所有帳戶]] 沒有更多新客戶或帳戶時中斷

預期輸出

| Account | Customer |
|---------|----------|
| A1      | C1       |
| A1      | C2       |
| A2      | C1       |
| A2      | C3       |
| A3      | C2       |
| A4      | C2       |
| A4      | C4       |

您可以使用分層查詢( CONNECT BY查詢)來完成此操作。 由於您正在瀏覽一個二分圖,因此您必須小心不要多次生成某些行; 我在 CONNECT BY 子句中這樣做,根據級別的奇偶性選擇一個條件或另一個條件。

如果需要,您可以將起始帳戶標識符(在下面的START WITH子句中硬編碼為“A1”)轉換為綁定變量。

with
     inputs ( account, customer ) as (
       select 'A1', 'C1' from dual union all       
       select 'A1', 'C2' from dual union all       
       select 'A2', 'C1' from dual union all
       select 'A2', 'C3' from dual union all
       select 'A3', 'C2' from dual union all
       select 'A4', 'C2' from dual union all
       select 'A4', 'C4' from dual union all
       select 'A5', 'C5' from dual union all
       select 'A6', 'C6' from dual
     )
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select account, customer
from   inputs
connect by nocycle 
  mod(level, 2) = 1 and account  = prior account
  or
  mod(level, 2) = 0 and customer = prior customer
start with account = 'A1'     -- Or make it a bind variable, if needed
order by account, customer    -- If needed
;

ACCOUNT  CUSTOMER
-------- --------
A1       C1      
A1       C2      
A2       C1      
A2       C3      
A3       C2      
A4       C2      
A4       C4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM