tags:

views:

119

answers:

2

My current query reads:

SELECT entry_id, user_id, cat_id, AVG( rating ) as avg_rate
FROM `entry_rate`
WHERE 1
GROUP BY entry_id

cat_id relates to different categories: 1, 2, 3 or 4

Is there a way I can find the maximum average for each user in each category without setting up an additional table? The return could potentially be 4 maximum avg_rate for each user_id

Visit the link below for example:

http://lh5.ggpht.com/_rvDQuhTddnc/S8Os_77qR9I/AAAAAAAAA2M/IPmzNeYjfCA/s800/table1.jpg

+2  A: 

May not be the most efficient way:

select user_id, cat_id, MAX(avg_rate)
FROM (
    SELECT entry_id, user_id, cat_id, AVG( rating ) as avg_rate
    FROM entry_rate
    GROUP BY entry_id, user_id, cat_id) t
GROUP BY user_id, cat_id
tloflin
You need to group by entry_id and user_id in the inner query as well.. Also, `WHERE 1` is not needed.
BlueRaja - Danny Pflughoeft
@BlueRaja, you're right, I just copied his query which also has those problems. Fixed.
tloflin
@tloflin and @BlueRaja- oh my God! you guys are wizards! I've been going over that for a while with no luck (granted I'm a newb...). THANK YOU!BTW, what is the 't' for on the end of the 5th line? That's the one element I don't understand.
Brad
That "t" is the name of the entity that you're selecting from. See how you've got that "from" keyword, and then the sub-query in parentheses? Well, it's treating the sub-query as a table, so it needs a name for the table (for instance, if you were to join it with another table, or if another table had a "user_id" field and you needed to distinguish them).
tloflin
So, if I'm understanding correctly, you named the sub-query "t" even though you weren't referencing it later in the query.(and I see that you can omit the label as...)
Brad
@Brad, right. It has to be named no matter what, but you don't have to reference it, just like you have to give a table name in a FROM clause but you don't have to use it anywhere else (unless there are conflicts).
tloflin
+1  A: 
SELECT s.user_id,s.cat_id,max(s.avg_rate) FROM (
  SELECT entry_id, user_id, cat_id, AVG( rating ) as avg_rate
  FROM entry_rate
  GROUP BY entry_id,user_id,cat_id) as s 
GROUP BY  s.user_id,s.cat_id
nos
This is also a great answer! Thanks (but a little too slow for the green check mark!)
Brad