Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average a column returned from a subquery

Tags:

sql

mysql

Is is not possible to average the results from a subquery?

Here's the query I'm fighting with:

SELECT AVG(
    SELECT SUM(`retail_subtotal`)
      FROM `order`
     WHERE `status` IN('O')
  GROUP BY `lead_id`
);
like image 379
Mikey1980 Avatar asked Jul 26 '12 18:07

Mikey1980


3 Answers

You need to create a subquery if you want to do this. By creating the subquery you then give the SUM() column a name and then AVG() that new field.

SELECT AVG(x.SubTotal)
FROM
(
    SELECT SUM(`retail_subtotal`) SubTotal
      FROM `order`
     WHERE `status` IN('O')
  GROUP BY `lead_id`
) x;
like image 145
Taryn Avatar answered Nov 01 '22 23:11

Taryn


Actually, an easier way to phrase the query is without a subquery:

SELECT SUM(`retail_subtotal`)/count(distinct lead_id) as avg
FROM `order`
WHERE `status` IN ('O')

(This assumes lead_id is never NULL.)

Your original query had a problem not only because of the subquery in the avg(), but also because the subquery returned multiple rows.

like image 42
Gordon Linoff Avatar answered Nov 02 '22 00:11

Gordon Linoff


Sure, just give the result column a name and select from it:

SELECT AVG(theSum)
FROM
(
    SELECT SUM(`retail_subtotal`) AS theSum
    FROM `order`
    WHERE `status` IN('O')
    GROUP BY `lead_id`
) T
like image 38
lc. Avatar answered Nov 02 '22 01:11

lc.