Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to get multiple values in one field

Author  Topic 

rsvore
Starting Member

15 Posts

Posted - 2012-02-22 : 13:27:48
I have this SQL query below that needs to return the distinct fields and it works. But each returned record my have more than one group_id that it belongs to so they will be listed multiple times. What I need is if the record has more than one group_id to list them in one field if that is possible. My goal is to list the records in a gridview in asp.net but not have multiple entries because of the group_id having multiple listings for a user.

example:
group_id Name
A1 Sue
A2 Sue
A2 Bob
A8 Ken

Need to have:
group_id Name
A1, A2 Sue
A2 Bob
A8 Ken

Select DISTINCT b.group_id, d.role_desc, c.role_cd, c.[admin], c.super_u, c.user_id,
a.lastname, a.fore_name, a.firstname, a.org,
a.job_title, a.active, a.last_on, a.lastupdate,
a.email_addr, c.date_on
FROM san.dbo.[security] AS a
INNER JOIN san.dbo.grpmems AS b ON a.user_id = b.grp_member
LEFT JOIN tms.dbo.imso_security AS c ON a.user_id = c.user_id
LEFT JOIN tms.dbo.[role] AS d ON c.role_cd = d.role_cd
WHERE a.active = 1 and a.lastname Like @alpha
ORDER BY a.lastname, a.firstname

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-02-22 : 15:00:59
Make the changes shown in red to your query:
;WITH cte AS
(

Select DISTINCT b.group_id, d.role_desc, c.role_cd, c.[admin], c.super_u, c.user_id,
a.lastname, a.fore_name, a.firstname, a.org,
a.job_title, a.active, a.last_on, a.lastupdate,
a.email_addr, c.date_on
FROM san.dbo.[security] AS a
INNER JOIN san.dbo.grpmems AS b ON a.user_id = b.grp_member
LEFT JOIN tms.dbo.imso_security AS c ON a.user_id = c.user_id
LEFT JOIN tms.dbo.[role] AS d ON c.role_cd = d.role_cd
WHERE a.active = 1 and a.lastname Like @alpha
)
SELECT DISTINCT
b.Groups,
a.*
FROM
cte a
OUTER APPLY
(
SELECT ','+b.group_id AS [text()]
FROM cte b
WHERE a.user_id = b.user_id
FOR XML PATH('')
) b(Groups)

ORDER BY
a.lastname,
a.firstname;
You need to be on SQL 2005 or higher for this to work.
Go to Top of Page

rsvore
Starting Member

15 Posts

Posted - 2012-02-22 : 15:07:48
Thanks for your help. I'm using SQL 2008.
Go to Top of Page
   

- Advertisement -