用于连接一列的SQL查询

时间:2011-12-29 10:25:51

标签: sql sql-server-2005

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

2 个答案:

答案 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

更多信息

STUFF (Transact-SQL)

答案 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;