Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transpose rows to single column

Tags:

sql

sql-server

I am using SQLServer. I have a query which gives the following result.

1 Apple
1 Banana
1 Orange

Is there anyway in SQL to traspose it to the following:

1 Apple Banana Orange
like image 427
Mahesh Avatar asked Sep 07 '25 02:09

Mahesh


1 Answers

SELECT id, names = STUFF((SELECT ' ' + name
    FROM dbo.[table] WHERE id = t.id
    FOR XML PATH(''), 
        TYPE).value(N'./text()[1]', N'nvarchar(max)'), 1, 1, '')
FROM dbo.[table] AS t
-- WHERE id = 1
GROUP BY id;
like image 134
Aaron Bertrand Avatar answered Sep 10 '25 03:09

Aaron Bertrand