FirmanHidayat
FirmanHidayat

Reputation: 347

Transpose Row to Column using SQL Server

Could you help me one case, below

I have an original table, like this:


+++++++++++++++++++++++++++
Col1 | Col2
+++++++++++++++++++++++++++
A    | 1
A    | 2
A    | 3
B    | 4
B    | 5

then I want a result is like this:


+++++++++++++++++++++++++++
Col1 | Col2
+++++++++++++++++++++++++++
A    | 1,2,3
B    | 4,5

How should I do this in SQL Server?

Upvotes: 1

Views: 1425

Answers (1)

Thit Lwin Oo
Thit Lwin Oo

Reputation: 3438

select distinct t.col1, (
SELECT STUFF(
(
    SELECT ',' + convert(varchar(10),col2)
    FROM TABLE
    where col1 = t.col1
    FOR XML PATH('')
), 1, 1, '') 
) col2
from TABLE t

Upvotes: 1

Related Questions