Depending on version of MSSQL you are using (2005+), you can use the FOR XML PATH
option.
SELECT
Name,
COUNT(*) AS ct,
STUFF((SELECT ',' + CAST(ID AS varchar(MAX))
FROM names i
WHERE i.Name = n.Name FOR XML PATH(''))
, 1, 1, '') as IDs
FROM names n
GROUP BY Name
ORDER BY ct DESC
Closest thing to group_concat
you'll get on MSSQL unless you use the SQLCLR option (which I have no experience doing). The STUFF
function takes care of the leading comma. Also, you don't want to alias the inner SELECT
as it will wrap the element you're selecting in an XML element (alias of TD
causes each element to return as <TD>value</TD>
).
Given the input above, here's the result I get:
Name ct IDs
Mike 3 1,3,5
John 2 0,2
Adam 1 4
EDIT: DISCLAIMER
This technique will not work as intended for string fields that could possibly contain special characters (like ampersands &
, less than <
, greater than >
, and any number of other formatting characters). As such, this technique is most beneficial for simple integer values, although can still be used for text if you are ABSOLUTELY SURE there are no special characters that would need to be escaped. As such, read the solution posted HERE to ensure these characters get properly escaped.