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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 put values on in one field
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

oasis1
Starting Member

34 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.

ie.
ID DXCode
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

TG
Flowing Fount of Yak Knowledge

USA
6062 Posts

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


;with yourTable (ID, DXCode)
as
(
       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]

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



Be One with the Optimizer
TG
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.08 seconds. Powered By: Snitz Forums 2000