2013-06-11 29 views
2

我有兩個表。表1包含唯一的帳戶號碼和唯一的帳戶名稱。表2包含與表1的帳號相關的帳號,但也包含另一個「父」帳號。查找缺失值,受其他值約束

我正在嘗試查找表1中存在的所有帳號,但不存在於表2中。此外,我希望每個表中缺少的每個「父」帳號都缺少帳號。

Ex。

表1

AccountNum AccountName 
1   a 
2   b 
3   c 
4   d 

表2

ParentAccount AccountNum AccountName 
100   1   a 
100   2   b 
200   1   a 
200   2   b 
200   4   d 

,我想我的結果返回:

100   3   c 
100   4   d 
200   3   c 

到目前爲止,我只能找出如何返回不值完全存在於表2中,但不受父母賬戶限制。我會分開表格,但我有數百個父帳戶。

SELECT Table1.AccountNum, Table1.AccountName 
FROM Table1 LEFT JOIN Table2 ON Table1.[AccountNum] = Table2.[AccountNum] 
WHERE (((Table2.AccountNum) Is Null)); 

任何幫助將不勝感激。我一直停留在這個相當一段時間,並在訪問我的工作2013年

回答

0

讓我們開始通過創建,讓我們ParentAccount和AccountNum的所有組合名爲[AccountCombinations]保存的查詢:

SELECT t2.ParentAccount, t1.AccountNum, t1.AccountName 
FROM 
Table1 t1, 
(
    SELECT DISTINCT ParentAccount FROM Table2 
) t2 

該查詢返回

ParentAccount AccountNum AccountName 
------------- ---------- ----------- 
      100   1 a   
      200   1 a   
      100   2 b   
      200   2 b   
      100   3 c   
      200   3 c   
      100   4 d   
      200   4 d   

現在我們就可以提取不表2中

SELECT * 
FROM AccountCombinations 
WHERE NOT EXISTS 
(
    SELECT * 
    FROM Table2 
    WHERE AccountCombinations.ParentAccount=Table2.ParentAccount 
     AND AccountCombinations.AccountNum=Table2.AccountNum 
) 
ORDER BY ParentAccount, AccountNum 
存在的那些

...正在返回...

ParentAccount AccountNum AccountName 
------------- ---------- ----------- 
      100   3 c   
      100   4 d   
      200   3 c   
+0

非常感謝!這正是我所需要的。 – user2476446