Написание SQL-запроса для MySQL и SQL Server - PullRequest
2 голосов
/ 19 октября 2011

у меня есть таблица следующей структуры

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 ]

4 голосов
/ 19 октября 2011

Для 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  
0 голосов
/ 20 октября 2011
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
0 голосов
/ 19 октября 2011

попробуй:

select name, SUM(field1),PROD(field2),AVG(field3) from table GROUP BY name 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...