这个SQL语句或存储过程怎么写?(50分)

  • 主题发起人 主题发起人 yanghaijun
  • 开始时间 开始时间
Y

yanghaijun

Unregistered / Unconfirmed
GUEST, unregistred user!
表的实际内容:
字段1 字段2 字段3 字段4 字段5
1 x y 2 a
1 x y 2 b
1 x y 2 c
2 m s p a
2 m s p f
...
要求返回:
字段1 字段2 字段3 字段4 字段5
1 x y 2 a,b,c
2 m s p a,f
...
即“字段5”的内容在前面4个字段内容相同的情况下,
其中的内容进行合并返回。
 
请先告知你的SQL服务器是哪一种?
 
create proc temp
as
begin
declare @f1 int,@f2 varchar(2),@f3 varchar(2),
@f4 varchar(2),@f5 varchar(2),@f6 varchar(20)
create table #temptable
( x1:integer,
x2:varchar(2),
x3:varchar(2),
x4:varchar(2),
x5:varchar(20)
)
set nocount on
declare same cursor for
select f1,f2,f3,f4,f5
from tablename
order by f1
open same
fetch next from same into @f1,@f2,@f3,@f4,@f5
while (@@fetch_status<>-1)
begin
@f6=@f6+@f5
if not exist(select * from #temptable where x1=@f1,x2=@f2,x3=@f3,x4=@f4)
begin
insert into #temptable(x1,x2,x3,x4,x5)
values (@f1,@f2,@f3,@f4,@f5)
@f6=@f5
end
else
begin
update #temptable set x5=@f6 where x1=@f1,x2=@f2,x3=@f3,x4=@f4
end
fetch next from same into @f1,@f2,@f3,@f4,@f5
end;
close same;
deallocate same
select * from #temptable order by x1
end;
瞎编的,怎么用游标不会
 
我用的是 MS SQL Server 7.0
 
to ugvanxk:
我按照你的思路基本上实现了,只是好象速度特别的慢,不知有没有
加快速度的方法。
 
看看你的数据量有多大?这种需求只能使用多层循环来实现,时间上的开销肯定会很大!

可以改进的地方:
假设源表为A,先生成中间表B:
create table B(f1,f2,f3,f4,f5) as select distinct(field1),distinct(field2),
distinct(field3),distinct(field4),'' from A group by field1,field2,field3,field4;
在存储过程中,
if not exist(select * from #temptable where x1=@f1,x2=@f2,x3=@f3,x4=@f4)
begin
insert into #temptable(x1,x2,x3,x4,x5)
values (@f1,@f2,@f3,@f4,@f5)
@f6=@f5
end
else
begin
update #temptable set x5=@f6 where x1=@f1,x2=@f2,x3=@f3,x4=@f4
end
这一段内容改写为:
update B set f5=f5+@field5 where f1=@field1 and f2=@field2 and ...
 
多人接受答案了。
 
后退
顶部