Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Register Now and get your question answered!
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 put values on in one field
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

35 Posts

Posted - 10/29/2013 :  13:41:26  Show Profile  Reply with Quote
Aloha all I ahve done this a while back abut can't remember how i put this together.

I have a list of patients that can have more than 1 diagnoses code.

1 47
1 25
1 17
1 20
2 87
2 23
2 92

I would like this to appear as so 47, 25, 17, 20 for record 1 and 87,23,92 for record 2. I believe I did this originally with the for xml funtion but couldn't remember how I moved to the next record without string everything on one line.

Mahalo for any help Brew

Flowing Fount of Yak Knowledge

6065 Posts

Posted - 10/29/2013 :  13:51:47  Show Profile  Reply with Quote
Here's one way:

;with yourTable (ID, DXCode)
       select 1, 47 union all
       select 1, 25 union all
       select 1, 17 union all
       select 1, 20 union all
       select 2, 87 union all
       select 2, 23 union all
       select 2, 92

select yt.[ID], stuff(max(x.DX), 1, 1, '') DXcodes
from yourTable yt
cross apply (
       select ',' + convert(varchar(50), DXCode)
       from   yourTable
       where  [ID] = yt.[ID]
       order by DXCode
       for xml path ('')
       ) x (DX)
group by yt.[ID]

ID          DXcodes
----------- ----------------
1           17,20,25,47
2           23,87,92

Be One with the Optimizer
Go to Top of Page
  Previous Topic Topic Next 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.04 seconds. Powered By: Snitz Forums 2000