Tuesday, March 20, 2012

Combine multiple results of subquery

Table users:
userid, name, added...

Table groups
groupid, groupname...

Table groupadmins:
userid, groupid

The users to groups relationship is many-to-many, which is why I created the intermediate table. I would like to return a recordset like:
userid, name, groupids
12344, 'Bob', '123,234,345'

If I try to just select groupid from groupadmins:
select userid, name, (select groupid from groupadmins where groupadmins.userid = users.userid) as groupids from users

then I'll get an error that a subquery is returning multiple results. Some users are not group admins and those that are may have a single or multiple groups. The only thing I can think of is to select the groupids seperately and use a cursor to loop through the results and build a string with the groupids. Then I would select the string with the rest of the fields that I want for return. Is there a better way to do this?

The best example of how to do this in this article by Aaron Bertrand:

http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html

If you are using SQL Server 2005, the FOR XML PATTH solution is really nice.

|||

Thanks a bunch. I tried googling and searching these forums, but without the right keywords, useful results can be hard to come by.

aspfaq.com is now bookmarked for many future references.

sqlsql

No comments:

Post a Comment