1

I have a table like this,

A         |        B
----------------------
1         |       10
1         |       20
2         |       30
2         |       40

I need output as,

A         |         B
------------------------
1         |        10,20
2         |        30,40

Thank you in advance

2
  • GROUP BY, and perhaps STUFF or GROUP_CONCAT or similar. Which data type for column B? Commented Jun 4, 2015 at 8:36
  • Its of int data type Commented Jun 4, 2015 at 8:52

1 Answer 1

3

Try this.

create table #table2(
    col1 int,
    col2 varchar(10),
)

insert into #table2
select 1, '10' union all
select 1, '20' union all
select 1, '30' union all
select 2, '40' union all
select 2, '50' union all
select 2, '60'


select
    col1,
    col2 = 
        stuff((
            select
                ', ' + t2.col2
            from #table2 t2
            where
                t2.col1 = t1.col1
            for xml path(''), type).value('.', 'varchar(max)'
        ), 1, 2, '')
from #table2 t1
GROUP BY t1.col1
Sign up to request clarification or add additional context in comments.

6 Comments

you don't really need a group by in your inner query in this example. you do need an order by
@ughai sorry. my mistake.not seen tag
I cant insert into another table like that because its having too many rows
@Giri Prasad : i haven't understood, explain briefly.
@Kumar I cant mention all the rows like you did in your answer coz my table is having many rows
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.