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.

Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top