How to Find Rows which are Duplicates by a Key but Not Duplicates in All Columns?

后端 未结 5 2064
逝去的感伤
逝去的感伤 2020-12-30 05:31

I am working with a table which is an extract of a set of other tables. All of the rows of the extract table should be unique according to keys D1, D2 and D3. They are not.

5条回答
  •  Happy的楠姐
    2020-12-30 06:05

    Any reason you don't just create another table expression to cover more fields and join to that one?

    WITH DUPLICATEKEY(D1,D2,D3) AS
    (
        SELECT D1, D2, D3
        FROM SOURCE
        GROUP BY D1, D2, D3
        HAVING COUNT(*)>1
    )
    WITH NODUPES(D1,D2,D3,C4,C5,C6) AS
    (
    SELECT 
    S.D1, S.D2, S.D3, S.C4, S.C5, S.C6
    FROM SOURCE S
    GROUP BY
     S.D1, S.D2, S.D3, S.C4, S.C5, S.C6
    HAVING COUNT(*)=1
    )
    
    SELECT S.D1, S.D2, S.D3, S.C4, S.C5, S.C6
    FROM SOURCE S
    INNER JOIN DUPLICATEKEY D
        ON S.D1 = D.D1 AND S.D2 = D.D2 AND S.D3 = D.D3
    
    INNER JOIN NODUPES D2
        ON S.D1 = D2.D1 AND S.D2 = D2.D2 AND S.D3 = D2.D3
    
    ORDER BY S.D1, S.D2, S.D3, S.C4, S.C5, S.C6
    

提交回复
热议问题