create table product(
id int identity(1,1),
_name varchar(max),
field1 int,
field2 int,
field3 int
)
create table #_name(
id int identity(1,1),
_name varchar(max),
field1 int,
field2 int,
field3 int
)
insert into product values ('aaa',20,30,40)
insert into product values ('aaa',40,50,60)
insert into product values ('bbb',40,50,60)
insert into product values ('aaa',75,55,60)
insert into product values ('bbb',20,30,40)
insert into product values ('bbb',40,50,60)
insert into product values ('ddd',40,50,60)
insert into product values ('ddd',40,50,60)
insert into product values ('ddd',40,50,60)
declare @name varchar(max);
declare @sum int,@prod int, @avg int;
declare @field2 int;
set @prod=1;
select * from product
declare pro_cursor cursor for
select p._name from (select distinct(_name) from product)p
open pro_cursor
fetch next from pro_cursor into @name
while(@@fetch_status=0)
begin
declare field_cursor cursor for
select field2 from product where _name=@name
open field_cursor
fetch next from field_cursor into @field2
while(@@fetch_status=0)
begin
set @prod=@prod*@field2;
fetch next from field_cursor into @field2
end
close field_cursor
deallocate field_cursor
set @sum=(select sum(field1) from product where _name=@name);
set @avg=(select avg(field3) from product where _name=@name);
insert into #_name values (@name,@sum,@prod,@avg)
set @prod=1;
fetch next from pro_cursor into @name
end
select * from #_name
close pro_cursor
deallocate pro_cursor
truncate table #_name