3

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
  • 1
    There must be at least 100 duplicates of this question (but I, too, am too lazy to search for them). Commented May 13, 2013 at 15:51

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

What about using CTE? "with CTE as ( select row_number() over(partition by employeename order by ID ) as rn from table )" - how to continue?
@HelenCraigman, not sure what you want to do with CTE that query show row number. for string concatenation, FOR XML is the better way.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.