I have a table UserAliases
(UserId, Alias
) with multiple aliases per user. I need to query it and return all aliases for a given user, the trick is to return them all in one column.
Example:
UserId/Alias
1/MrX
1/MrY
1/MrA
2/Abc
2/Xyz
I want the query result in the following format:
UserId/Alias
1/ MrX, MrY, MrA
2/ Abc, Xyz
Thank you.
I'm using SQL Server 2005.
p.s. actual T-SQL query would be appreciated :)
Well... I see that an answer was already accepted... but I think you should see another solutions anyway:
My boss wrote up an article on this way back 2003: Concatenation with COALESCE
Sorry, read the question wrong the first time. You can do something like this:
You can either loop through the rows with a cursor and append to a field in a temp table, or you could use the COALESCE function to concatenate the fields.
group_concat() sounds like what you're looking for.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
since you're on mssql, i just googled "group_concat mssql" and found a bunch of hits to recreate group_concat functionality. here's one of the hits i found:
http://www.stevenmapes.com/index.php?/archives/23-Recreating-MySQL-GROUP_CONCAT-In-MSSQL-Cross-Tab-Query.html
this is one of the fastest and simplest ways to do what you need without the need for a UDF: http://weblogs.sqlteam.com/mladenp/archive/2007/06/01/60220.aspx
there's one other way using a numbers table that is faster for really large datasets but i don't think you'll need that.