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
 rows into columns
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

tikoti
Starting Member

4 Posts

Posted - 01/29/2013 :  05:24:42  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 01/29/2013 :  05:31:55  Show Profile  Reply with Quote

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/


Edited by - visakh16 on 01/29/2013 05:32:28
Go to Top of Page

tikoti
Starting Member

4 Posts

Posted - 01/29/2013 :  05:56:10  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 01/29/2013 :  05:57:57  Show Profile  Reply with Quote
welcome

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

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