TABLE-A的数据如下:
COLUMN1 COLUMN2
1 A
1 B
1 C
2 A
2 G
3 F
4 T
4 K
我想要RESULT如下:
COLUMN1 COLUMN2
1 A,B,C
2 A,G
3 F
4 T,K
答案 0 :(得分:7)
您可以使用T-SQL
函数STUFF
。
SELECT COLUMN1, STUFF((
select ','+ COLUMN2
from YourTableName b
WHERE a.COLUMN1 = b.COLUMN1
FOR XML PATH('')
)
,1,1,'') AS COLUMN2
FROM YourTableName a
GROUP BY a.COLUMN1
答案 1 :(得分:0)
create table #con(
column1 int,
column2 varchar(10)
)
declare @column2 varchar(10), @col2 varchar(10)
declare @column1 int;
declare con_cursor cursor for
select column1, column2 from con
open con_cursor
fetch next from con_cursor into @column1, @column2
while(@@fetch_status=0)
begin
if(@column1 not in (select column1 from #con))
begin
insert into #con values (@column1, @column2);
end
else
begin
set @col2 = (select column2 from #con where column1=@column1);
update #con set column2=(@col2+','+@column2) where column1=@column1;
end
fetch next from con_cursor into @column1, @column2
end
select * from #con;
close con_cursor;
deallocate con_cursor;
truncate table #con;