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.
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 MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
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 BirthsJim 002-45 DeathsJane 002-55 BirthsJack 002-30 BirthsJean 002-30 BirthsJackie 004-34 DeathsJon 002-30 BirthsJuan 564-34 DeathsWhen 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 JonWhat I need is them formatted onto one row like this.Name:John; Jack; Jean; JonI hope that makes better sense.Thanks |
 |
|
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 |
 |
|
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 MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
 |
|
|
|
|
|
|