2014-01-07 51 views
0

我有一個查詢用於檢查重複地址(基於具有相同的地址行1,地址行2和郵政編碼),但如果transactionType爲1,則不應顯示記錄「斷開」的,「DeEnrollDeceased」,「DeEnrollLeaving」,「DeEnrollFailedRecertification」,「DeEnrollNonUsage」或者如果iehFlag沒有設置爲0。用於檢查重複項的SQL查詢

因此,如果兩個記錄有相同的地址,但一個是「斷開」和另一個不是,那麼這兩個記錄都不應該返回。此外,如果兩個記錄具有相同的地址,但一個是iehFlag = 0,另一個是iehFlag = 1,則不應返回。目前,我在這兩種情況下都返回了。

我將不勝感激在哪裏我的查詢是怎麼了?任何幫助

SELECT 'Address' DuplicateType, iehFlag, transactionType, AccountNumber, AccountType, firstName, lastName, last4ssn, tribalId, dob, phoneNumber 
FROM table a, 
    (SELECT primaryAddress1, COALESCE(primaryAddress2, '') address2, primaryZipCode 
    FROM table 
    WHERE transactionType NOT IN ('Disconnect', 'DeEnrollDeceased', 'DeEnrollLeaving', 'DeEnrollFailedRecertification', 'DeEnrollNonUsage') 
     AND iehFlag = 0 
    GROUP BY primaryAddress1, primaryAddress2, primaryZipCode 
    HAVING COUNT(AccountNumber) > 1) b 
WHERE a.primaryAddress1 = b.primaryAddress1 
    AND COALESCE(a.primaryAddress2, '') = b.address2 
    AND a.primaryZipCode = b.primaryZipCode 
ORDER BY a.primaryAddress1 

回答

0

試試這個:

SELECT 'Address' DuplicateType, iehFlag, transactionType, AccountNumber, AccountType, firstName, lastName, last4ssn, tribalId, dob, phoneNumber 
FROM table a, 
    (SELECT primaryAddress1, COALESCE(primaryAddress2, '') address2, primaryZipCode, COUNT(*) 
    FROM table 
    WHERE iehFlag = 0 
    GROUP BY primaryAddress1, primaryAddress2, primaryZipCode 
    HAVING COUNT(*) > 1) b 
WHERE a.primaryAddress1 = b.primaryAddress1 
    AND COALESCE(a.primaryAddress2, '') = b.address2 
    AND a.primaryZipCode = b.primaryZipCode 
    AND transactionType NOT IN ('Disconnect', 'DeEnrollDeceased', 'DeEnrollLeaving', 'DeEnrollFailedRecertification', 'DeEnrollNonUsage') 
ORDER BY a.primaryAddress1 

具有SELECT子句中的COUNT(*)和HAVING子句應該正確標記具有多個實例的數據。如果有什麼不清楚,請告訴我。

+0

斷開連接的記錄仍顯示爲 – Jason

+0

對不起,延遲迴復。嘗試將「Where事務類型不在」子句移動到外部查詢中。我已經更新了我的答案以表示此更改。 – Sev09

+0

另外,我知道它看起來很基本,但要確保transactionType的這些值拼寫正確。 – Sev09