简体   繁体   中英

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;

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM