August 11, 2015 at 3:28 pm
Hi I'm hoping somebody has a slick sql trick that can show me. I have about 100 K records of the form below in Example 1 and I would like to turn them into the form of Example 2, basically turn the entries in field2 into a coma separated list of values sorted by field1.
Example 1:
field1_field2
1_____a
1_____b
1_____c
2_____f
2_____g
and I would like to get it in the form
Example 2:
field1_field3
1_____a,b,c
2_____f,g
August 11, 2015 at 3:48 pm
Give this a try.
select distinct
mt.field1,
ca.field3
from
dbo.MyTable mt
cross apply (select stuff((select ',' + mt1.field2
from dbo.MyTable mt1
where mt1.field1 = mt.field1
for xml path(''),TYPE).value('.','varchar(max)'),1,1,''))ca(field3);
August 11, 2015 at 4:19 pm
Lynn Pettis (8/11/2015)
Give this a try.
select distinct
mt.field1,
ca.field3
from
dbo.MyTable mt
cross apply (select stuff((select ',' + mt1.field2
from dbo.MyTable mt1
where mt1.field1 = mt.field1
for xml path(''),TYPE).value('.','varchar(max)'),1,1,''))ca(field3);
And you can read all about how this works at this article[/url].
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply