SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to get multiple values in one field
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rsvore
Starting Member

USA
15 Posts

Posted - 02/22/2012 :  13:27:48  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 02/22/2012 :  15:00:59  Show Profile  Reply with Quote
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

USA
15 Posts

Posted - 02/22/2012 :  15:07:48  Show Profile  Reply with Quote
Thanks for your help. I'm using SQL 2008.
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.11 seconds. Powered By: Snitz Forums 2000