Say we have a table #test with columns as follows::
I need to display rows as follows:
We can use FOR XML PATH concept to accomplish this:
QUERY:
First we will create table #test::
CREATE TABLE #test(
field1 VARCHAR(5), field2 VARCHAR(5)
)
Let us first create table #test:
INSERT INTO #test
SELECT '001','AAA'
UNION ALL
SELECT '001','BBB'
UNION ALL
SELECT '002','CCC'
UNION ALL
SELECT '003','DDD'
UNION ALL
SELECT '004','EEE'
UNION ALL
SELECT '004','FFF'
UNION ALL
SELECT '004','GGG'
For required output, the query will be
SELECT field1, SUBSTRING ( (SELECT ( ', ' + field2)
FROM #test t2
WHERE t1.Field1 = t2.Field1
ORDER BY t1.Field1, t2.Field1
FOR XML PATH (' ')), 3, 1000)
FROM #test t1
GROUP BY field1
Comments
Post a Comment