我有一张下列结构的表

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中实现这一点。

最佳答案

对于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

关于mysql - 为MySQL和SQL Server编写SQL查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7819818/

10-13 08:53