Yeol Yeol - 1 month ago 9
MySQL Question

MySQL: How do I check which entries for each group has a value greater than the average values in its corresponding group?

I need to show the values of each group (formed by GROUP BY) that has a value greater than the average values of the group it belongs in. I tried to do:

WHERE price > (SELECT AVG(I.price)
FROM items I, category C
WHERE I.itemcode = C.itemcode
GROUP BY C.category)

but it returns multiple rows so it cant be used with the ">" operator.
That said, how can I do this? Thanks in advance!

edit:
here's the complete query
SELECT C.category, I.itemname, I.price
FROM item I INNER JOIN category C on I.itemcode = C.itemcode
WHERE I.price > (SELECT AVG(I.price) FROM items I, category C WHERE I.itemcode = C.itemcode GROUP BY C.category)
ORDER BY 1, 2;

Answer

What you need is correlated querys.

Set an alias for your Category table in your main query, then use that alias in your subquery.

SELECT C.category, I.itemname, I.price 
FROM item I INNER JOIN category C on I.itemcode = C.itemcode 
WHERE I.price > (SELECT AVG(Itm.price) FROM items Itm, category Cat 
           WHERE Itm.itemcode = Cat.itemcode 
           and Cat.cateogry = C.category) 
ORDER BY 1, 2;

The magic is here Cat.category = C.category C is Cateogry table in the main query while Cat is the same Cateogry table of the subquery.

So, it will calculate the average Item price of the items that have the same category than the item being queried at the main query.

Have in mind, that this is not performance-friendly, as it might calculate the average price once every record in your main query. So be careful.

A better approach is to use Joins as pointed out by @Summer-Sky

Comments