MySQL中的非聚合平均值?

时间:2012-02-26 13:45:41

标签: mysql average

有没有办法计算子查询返回的结果的平均值而不使用聚合函数?

假设的例子:

我想为每个帐户选择一个月内的平均最高发票。我希望能够做到这样的事情:

SELECT
   accounts.*,
   **AVERAGE**(SELECT MAX(`amount`)
               FROM invoices
               WHERE invoices.account_id = accounts.id
               GROUP BY invoices.month) as `average_max`

1 个答案:

答案 0 :(得分:2)

根据定义,平均值是一个聚合函数,因为它需要对数据汇总进行操作。

为了得到你想做的事我会做:

SELECT
  accounts.*, avg_amount.amount AS avg_amount
FROM
  accounts
LEFT JOIN (
  SELECT account_id, AVG(amount) AS amount FROM (
    SELECT month, account_id, MAX(amount) AS amount FROM invoices GROUP BY month, account_id
  ) AS max_amount USING(account_id)
) AS avg_amount ON (accounts.id = avg_amount.account_ID)