Possible Duplicate:
Combine multiple results in a subquery into a single comma-separated value
Concat groups in SQL Server
I want to be able to get the duplication’s removed
SELECT Count(Data) as Cnt, Id
FROM [db].[dbo].[View_myView]
Group By Data
HAVING Count(Data) > 1
In MySQL it was as simple as this:
SELECT Count(Data), group_concat(Id)
FROM View_myView
Group By Data
Having Cnt > 1
Does anyone know of a solution? Examples are a plus!
In SQL Server as of version 2005 and newer, you can use a CTE (Common Table Expression) with the
ROW_NUMBERfunction to eliminate duplicates:This CTE “partitions” your data by
UserID, and for each partition, theROW_NUMBERfunction hands out sequential numbers, starting at 1 and ordered byCreated DESC– so the latest row getsRowNum = 1(for eachUserID) which is what I select from the CTE in the SELECT statement after it.Using the same CTE, you can also easily delete duplicates:
Same principle applies: you “group” (or partition) your data by some criteria, you consecutively number all the rows for each data partition, and those with values larger than 1 for the “partitioned row number” are weeded out by the
DELETE.