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
 rows into columns

Author  Topic 

tikoti
Starting Member

4 Posts

Posted - 2013-01-29 : 05:24:42
Hi all!

I have a question

I have two tables 1-N related e.g.

1 car
2 bus
3 bycicle

and a second one with multiple rows for each item in the previous table

1 wheels
1 seat
2 big
2 driver
2 school
3 cheap

How can i obtain with an t-sql statement the following output

car wheels,seat
bus big,driver,school
bycicle chea

Thank you all!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-29 : 05:31:55
[code]
SELECT t1.description as t1desc,
STUFF((SELECT ',' + description FROM table2 WHERE id = t1.id FOR XML PATH('')),1,1,'') AS descriptions
FROM table1 t1
[/code]
I've assumed column names so make sure you put correct column names instead

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

tikoti
Starting Member

4 Posts

Posted - 2013-01-29 : 05:56:10
Wow this is absolutely great!

Thank you!

quote:
Originally posted by visakh16


SELECT t1.description as t1desc,
STUFF((SELECT ',' + description FROM table2 WHERE id = t1.id FOR XML PATH('')),1,1,'') AS descriptions
FROM table1 t1

I've assumed column names so make sure you put correct column names instead

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/



Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-29 : 05:57:57
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -