注册 登录
编程论坛 SQL Server论坛

这个SQL 比较急

sm105096496 发布于 2007-09-26 16:21, 528 次点击

问个sql语句
表A
字段1 字段2 字段3 字段4
1 a1 b1 c1
1 a1 b1 c2
2 a2 b2 c1
2 a2 b2 c2
2 a2 b2 c3

现在我想获得的结果是:
1 a1 b1 c1,c2
2 a2 b2 c1,c2,c3
在sql中能实现吗??

2 回复
#2
purana2007-09-26 17:23

[CODE]create table #a
(
col int,
col_1 varchar(2),
col_2 varchar(2),
col_3 varchar(2),
)
insert into #a values (1,'a1','b1','c1')
insert into #a values (1,'a1','b1','c2')
insert into #a values (2,'a2','b2','c1')
insert into #a values (2,'a2','b2','c2')
insert into #a values (2,'a2','b2','c3')
create table #result
(
col int,
col_1 varchar(2),
col_2 varchar(2),
col_3 varchar(100),
)
delete #result
declare @col int,@col_1 varchar(2),@col_2 varchar(2),@col_3 varchar(2)
declare a_cursor cursor
for
Select col,col_1,col_2,col_3 from #a
open a_cursor
fetch next from a_cursor into @col,@col_1,@col_2,@col_3
while @@fetch_status=0
begin
if not exists(select * from #result where col=@col and col_1=@col_1 and col_2=@col_2)
begin
insert into #result values (@col,@col_1,@col_2,@col_3)
end
else
begin
update #result set col_3=col_3+','+@col_3 where col=@col and col_1=@col_1 and col_2=@col_2
end
fetch next from a_cursor into @col,@col_1,@col_2,@col_3
end
close a_cursor
deallocate a_cursor
SELECT * FROM #result[/CODE]

#3
shuzai19852007-09-26 18:00
写一个函数就可以了...
create function Gettxt(@字段1 char)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s +',' +字段4 from csdn where 字段1=@字段1
--return @s
return stuff(@s,1,1,'')
end
go
select 字段1,字段2,字段3,dbo.Gettxt(字段1) as 字段4 from csdn group by 字段1
go
1