Wednesday, July 3, 2013

Clubbing of one column based on referring(grouping) of other column

Comments :- 
In below example,I have a #temp table with 2 columns named A,B

Here I am applying group by clause on 'B' column and getting 'A' column's
CSV(comma separated values) correspond to grouping.


Example :- 
create table #temp
(
a int,
b varchar(10)
)

insert into #temp
select 1,'A'
union all
select 2,'A'
union all
select 1,'B'
union all
select 2,'B'


select * from #temp

;with temptable as
(
select b from #temp group by b
)

select  stuff((select ','+ cast(#temp.a as varchar)
  from #temp
  where #temp.b=temptable.b
  for xml path('')),1,1,'')
,temptable.b
from temptable

drop table #temp


Main table structure :- 


Final Result :- 

No comments:

Post a Comment