Home:ALL Converter>Oracle SQL - Comparing AVG functions in WHERE

Oracle SQL - Comparing AVG functions in WHERE

Ask Time:2013-11-29T07:54:12         Author:Cucko Oooo

Json Formatter

I'm trying to write a few Oracle SQL scripts for an assignment. I've managed to get all of it to work, except for one part. To summarize, I have to display data from 2 tables if the average of 1 column in table A is greater than the average of another column in table B. I realize you cannot include AVG functions in a WHERE clause or HAVING clause since it seems unable to properly access the data (from what I've read). When I exclude this clause, the script executes properly, so I'm confident there are no other errors.

I've tried writing it as follows but the error I get is ORA-00936: missing expression and it is just before the > sign. I thought this may be due to improper bracket placing but none of my attempts resolved this. Here is my attempt:

SELECT l.l_category, SUM(r.r_sold), AVG(l.l_cost)
FROM promos l 
    INNER JOIN sales r 
        ON r.promo_id = l.promo_id
GROUP BY l.l_category
HAVING (SELECT AVG(l.l_cost) OVER (PARTITION BY l.l_cost)) > 
    (SELECT AVG(r.r_sold)   OVER (PARTITION BY r.r_sold));

I tried doing this without the OVER (PARTITION BY ...) as well as putting it into a WHERE clause but it didn't resolve the error. I'm pretty sure I need to put it into a SELECT statement somehow but I'm at a loss.

Author:Cucko Oooo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/20276399/oracle-sql-comparing-avg-functions-in-where
yy