I am having a hard time with what should be a simple query. I have studied the documentation on the AVG function and understand that I may need to execute this with a subquery. This is the gist of what I want to accomplish – finding values greater than 3 * the average of the non-zero values of a column. Here is what I thought would work. Any help appreciated.
SELECT COL1, COL2
FROM TABLE1
HAVING COL3 > 0 AND COL3 > AVG(COL3*3)
ORDER BY COL1;
Best Answer
For that version of
AVG()
, you need toGROUP BY
on the columns, but that way your average value would be incorrect. Sure you can use a subquery (where you do not reference any other column, and because of that, you do not need aGROUP BY
inside), for example:But this will perform 2 index/table scans, that work can be reduced by using the analytic version of
AVG()
:Edit: forgot about the greater than zero condition, including that:
And: