SQL Server:根据单个列中的值在表中查找重复项

时间:2013-05-13 14:54:24

标签: sql sql-server duplicates duplicate-data

我有一个SQL Server表,其中包含以下字段和示例数据:

ID   employeename
1    Jane
2    Peter
3    David
4    Jane
5    Peter
6    Jane

ID列每行都有唯一值。

employeename列有重复项。

我希望能够根据employeename列找到重复项,并列出以逗号分隔的重复项的ID

上述样本数据的预期输出:

employeename   IDs
Jane           1,4,6
Peter          2,5

表中还有其他列我不想考虑此查询。

感谢您的帮助!

2 个答案:

答案 0 :(得分:6)

select
 employeename,
 IDs = STUFF((SELECT ','+ CAST(e2.[ID] AS VARCHAR(10)) 
  FROM emp e2
  WHERE e2.employeename = e1.employeename
  For XML PATH('')
 ),1,1,'')
FROM emp e1
GROUP BY employeename having COUNT(*) > 1

SQL Fiddler

答案 1 :(得分:0)

这是Northwind示例:

Use Northwind
GO

SELECT
   ord1.CustomerID,
   OrderIdList = substring((SELECT ( ', ' + convert(varchar(16) , OrderID) )
                           FROM [dbo].[Orders] ord2
                           WHERE ord1.CustomerID = ord2.CustomerID
                           ORDER BY 
                              CustomerID,
                              OrderID
                           FOR XML PATH( '' )
                          ), 3, 1000 )FROM [dbo].[Orders] ord1
GROUP BY CustomerID