为MySQL和SQL Server编写SQL查询

时间:2011-10-19 10:23:00

标签: mysql sql sql-server-2005

我有一个以下结构的表

id name field1 field2 field3
1  aaa   20     30     40
2  aaa   40     50     60
3  bbb   40     50     60
4  aaa   75     55     60
5  bbb   40     50     60
6  bbb   40     50     60

我想要的结果集是

1 aaa (sum of field 1) (product of field 2) (average of field3)
2 bbb (sum of field 1) (product of field 2) (average of field3)

我无法找到如何做到这一点。我试过了

select SUM(field1),PROD(field2),AVG(field3) from table GROUP BY name 

但它不起作用。另外我还需要了解如何在sql server 2005中执行此操作。

3 个答案:

答案 0 :(得分:4)

对于SQL Server,您可以使用

SELECT SUM(field1),
       CASE
         WHEN COUNT(CASE
                      WHEN field2 = 0 THEN 1
                    END) > 0 THEN 0
         ELSE 1
       END * CASE COUNT(CASE WHEN SIGN(field2) = -1 THEN 1 END )%2
               WHEN 0 THEN 1
               ELSE -1
             END * EXP(SUM(LOG(ABS(NULLIF(field2, 0))))),
       AVG(field3)
FROM   T
GROUP  BY name  

答案 1 :(得分:0)

尝试:

select name, SUM(field1),PROD(field2),AVG(field3) from table GROUP BY name 

答案 2 :(得分:0)

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