2016-12-05 31 views
2

我已經做了一個查詢來檢查重複的項目,並顯示重複的ID在不同的列而不是不同的行。在不同的列中顯示重複的項目/ ID

SELECT uid, COUNT(*), Max(id) AS dupes1, MIN(id) AS dupes2 
FROM table 
GROUP BY uid 
HAVING (COUNT(*) > 1) 

另一組查詢

SELECT y.uid, x.id 
FROM table x 
JOIN (SELECT t.uid 
     FROM table t 
    GROUP BY t.uid 
    HAVING COUNT(t.uid) > 1) y ON y.uid = x.uid 
    where Len(y.uid) > 11 
    order by y.uid 

也能正常工作2重複的項目的,但我想顯示在不同的列

預期輸出的所有重複項

uid count dupes1 dupes2 dupes3 and so on...

+0

如果有3行具有相同的uid,那麼預期的結果是什麼?添加一些示例表數據,並且預期結果 – jarlh

+0

結果應該如下: id,count,dup1,dup2,dup3 –

+0

@ArijitMukherjee然後您需要動態sql來這樣做 – Eric

回答

2
SELECT uid, COUNT(*), 
-- A varchar column to show all duplicates with the format 1,2,3 
STUFF((
    SELECT ',' + CAST(id AS varchar(10)) FROM table b WHERE a.uid = b.uid FOR XML PATH ('') 
), 1, 1, '') AS dupes 
FROM table a 
GROUP BY uid 
HAVING (COUNT(*) > 1) 
+0

是的,我想這樣的結果,但它有可能得到在不同的列而不是單列 –