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
 SQL select statement that groups results

Author  Topic 

Stuart100
Starting Member

3 Posts

Posted - 2013-12-16 : 07:48:37

I have a table with three columns. Name, book#, category.

I need to write a select statement that looks at the book# and category and returns all the names that match that into one joined our combined result. So if my name column had john, Jane, Jim, jack, and Steph in unique rows that matched it would bring back a resulted formatted as. John, Jane, Jim, jack, Steph. So I could place that in a field for reference.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-16 : 07:51:08
[code]
SELECT STUFF((SELECT ',' + Name
FROM Table WHERE [Book#] = t.[Book#]
AND category = t.category
FOR XML PATH('')),1,1,'') AS Names,
[Book#],
[category]
FROM (SELECT DISTINCT [book#], category FROM table)t
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

Stuart100
Starting Member

3 Posts

Posted - 2013-12-18 : 11:44:41
Ok so maybe I missed something but this is not producing the results I need.

Maybe a little better description is in order.
I have a table with three columns.

Name: Book#: Category:
John 002-30 Births
Jim 002-45 Deaths
Jane 002-55 Births
Jack 002-30 Births
Jean 002-30 Births
Jackie 004-34 Deaths
Jon 002-30 Births
Juan 564-34 Deaths

When I run this select statement I am close to what I need.

Select name from dbo.Archives where book# = '002-30' and category = 'births'

The only issue it returns all the name in rows. What I need is all the names grouped and divided by a , or ;

For example if I ran that select statement I would get back:

Name:
John
Jack
Jean
Jon

What I need is them formatted onto one row like this.

Name:
John; Jack; Jean; Jon

I hope that makes better sense.

Thanks
Go to Top of Page

Stuart100
Starting Member

3 Posts

Posted - 2013-12-18 : 13:06:17
Got it.

DECLARE @Results VARCHAR(max)
SELECT @Results= COALESCE(@Results + '; ', '') + rtrim (name)
FROM dbo.Archives where book# = '01-004' and category = 'Death 1893-1906'
select @Results AS Combined
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-12-19 : 03:29:57
[code]
SELECT STUFF((SELECT DISTINCT ',' + Name
FROM Table
FOR XML PATH('')),1,1,'') AS Names
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -