SQL Server : find duplicates in a table based on values in a single column

江枫思渺然 提交于 2019-11-28 05:20:40

问题


I have a SQL Server table with the following fields and sample data:

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

The ID column has unique values for each row.

The employeename column has duplicates.

I want to be able to find duplicates based on the employeename column and list the IDs of the duplicates next to them separated by commas.

Output expected for above sample data:

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

There are other columns in the table that I do no want to consider for this query.

Thanks for all your help!


回答1:


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




回答2:


Here is a Northwind example:

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


来源:https://stackoverflow.com/questions/16525064/sql-server-find-duplicates-in-a-table-based-on-values-in-a-single-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!