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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 put values on in one field

Author  Topic 

oasis1
Starting Member

35 Posts

Posted - 2013-10-29 : 13:41:26
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
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-10-29 : 13:51:47
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
   

- Advertisement -