在不同列中显示重复项/ ID

时间:2016-12-05 08:29:03

标签: sql sql-server duplicates

我已经查询了重复的项目,并在不同的列而不是不同的行中显示重复的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...

1 个答案:

答案 0 :(得分: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)