How to calculate a static average value of all rows in a Table to compare individual row values to in Oracle SQL

StackOverflow https://stackoverflow.com/questions/23507348

  •  16-07-2023
  •  | 
  •  

Question

I need to calculate a static average value of all rows in a Table to compare individual row values against. Here is what I have come up with so far:

SELECT i.ITEM_NAME, i.ITEM_PRICE
  FROM ITEM i
  GROUP BY i.ITEM_NAME, i.ITEM_PRICE
  HAVING i.ITEM_PRICE > AVG(i.ITEM_PRICE)
  ORDER BY i.ITEM_PRICE DESC, i.ITEM_NAME ASC;

My problem is that the average that is being used to compare a row's ITEM_PRICE against is being calculated for only said row's ITEM_PRICE (an average of one number). Is there anyway within this query that I could obtain a static average of all of the rows' ITEM_PRICEs to compare the individual ITEM_PRICE for each row against? I think the problem may be in the way the GROUP BY correlates the values, but I'm not sure.

Was it helpful?

Solution

Since you only want to calculate the average of all rows, you could forego grouping, and just use a WHERE clause to compare the price against average. Code would be something like:

select item_name, item_price
from item
where item_price > (select avg(item_price) from item)
order by item_price desc, item_name asc

Of course, this assumes that you have only one row for one item_name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top