0

当我尝试对列进行平均处理然后我想对结果求和时遇到了麻烦,我正在使用 MYSQL 来做到这一点。谁能帮我?这是不起作用的查询:

SUM(IF(AVG(Value)=3,1,0)) AS green

完整查询:

SELECT
  cluster,
  SUM(IF(AVG(Value) AS Value = 3,1,0)) AS green
FROM network
WHERE date>= '2012-07-01'
    AND date<= '2012-07-02'
    AND Region = 'SOMEREG'
    AND cluster IS NOT NULL
GROUP BY cluster
4

3 回答 3

0

只需这样做

SELECT
  IFNULL(cluster,'Total'),
  SUM(IF(AVG(Value) AS Value = 3,1,0)) AS green
FROM network
WHERE date>= '2012-07-01'
    AND date<= '2012-07-02'
    AND Region = 'SOMEREG'
    AND cluster IS NOT NULL
GROUP BY cluster with roll up

添加汇总它将添加所有平均值

于 2012-07-25T09:08:19.360 回答
0

您一次只能应用一个聚合函数。

同一 group by 子句的多个聚合函数没有意义。您需要创建派生表来查找平均值的总和。尝试:

SELECT SUM(green) AS green
FROM (
      SELECT cluster,
             IF(AVG(Value) = 3, 1, 0) AS green
      FROM network
      WHERE date BETWEEN '2012-07-01' AND '2012-07-02'
            AND Region = 'SOMEREG'
            AND cluster IS NOT NULL
      GROUP BY cluster
     ) a;
于 2012-07-25T07:50:41.333 回答
0
That should not be an if, but a where in the select statement.

SELECT cluster,
SUM(Value) AS sumValue AVG(Value) AS avgValue
FROM network
WHERE date>= '2012-07-01'
AND date<= '2012-07-02'
AND Region = 'SOMEREG'
AND ((AVG(Value) = 3) OR (AVG(Value) = 1) OR (AVG(Value) = 0))
AND cluster IS NOT NULL
GROUP BY cluster
于 2012-07-25T07:37:45.357 回答