Yeol
Yeol

Reputation: 139

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;

Upvotes: 0

Views: 84

Answers (2)

Freddy Hdz
Freddy Hdz

Reputation: 137

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

Upvotes: 1

Summer-Sky
Summer-Sky

Reputation: 481

alternatively

SELECT C.category, I.itemname, I.price 
FROM items I 
INNER JOIN category C on I.itemcode = C.itemcode 
JOIN (
    SELECT C.category, AVG(I.price) avgprice  
    FROM items I, category C 
    WHERE I.itemcode = C.itemcode 
    GROUP BY C.category) A on A.category = C.category
WHERE I.price > A.avgprice  ORDER BY 1, 2;

Upvotes: 1

Related Questions