Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

concatenating column values in a row

Status
Not open for further replies.

chopstix21

Technical User
May 23, 2012
2
0
0
RO
i need to concatenate x values which are grouped by id, ordering them by y column from subquery.
Subquery looks like this
id x y
1 1 1
1 2 3
1 3 2
2 1 null
2 2 1
3 1 1
3 2 2
4 1 null
4 2 null
final results should look like
id result
1 1,3,2
2 2
3 1,2
4 null
 
The following should get you what you need. Just replace "YourTable" in the From statements with the name of your table.


Code:
SELECT A.ID, 
Result=STUFF((
	      select ',',convert(varchar,B.X)
	      From YourTable B
	      Where B.ID=A.ID
	      Order by B.Y
	      for XML Path('')
	      ),1,1,'')
From YourTable A
Group By A.ID
Order By A.ID
 
To match the OP's result set
Code:
SELECT A.ID, 
Result=STUFF((
	      select ',',convert(varchar,B.X)
	      From YourTable B
	      Where B.ID=A.ID [b][red] AND B.Y is not NULL[/red][/b]
	      Order by B.Y
	      for XML Path('')
	      ),1,1,'')
From YourTable A
Group By A.ID
Order By A.ID

soi là, soi carré
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top