标题:这个SQL 比较急
只看楼主
sm105096496
Rank: 1
等 级:新手上路
帖 子:58
专家分:0
注 册:2007-7-11
 问题点数:0 回复次数:2 
这个SQL 比较急

问个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中能实现吗??

搜索更多相关主题的帖子: SQL 
2007-09-26 16:21
purana
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:广东-广州
等 级:版主
威 望:66
帖 子:6039
专家分:0
注 册:2005-6-17
得分:0 

[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]


我的msn: myfend@
2007-09-26 17:23
shuzai1985
Rank: 1
等 级:新手上路
帖 子:22
专家分:0
注 册:2007-8-22
得分:0 
写一个函数就可以了...
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
2007-09-26 18:00



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-173060-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.121601 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved