MYSQL - Group by limit

Posted by jono2010 on Stack Overflow See other posts from Stack Overflow or by jono2010
Published on 2010-04-15T07:05:53Z Indexed on 2010/04/15 7:13 UTC
Read the original article Hit count: 444

Filed under:
|
|

Hello

Is there a simple way to LIMIT the GROUP BY results to the top 2. The following query returns all the results. Using 'LIMIT 2' reduces the overall list to the top 2 entries only.

select distinct(rating_name), 
       id_markets, 
       sum(rating_good) 'good', 
       sum(rating_neutral)'neutral', 
       sum(rating_bad) 'bad' 
 from ratings 
 where rating_year=year(curdate()) and rating_week= week(curdate(),1)
 group by rating_name,id_markets
 order by rating_name, sum(rating_good) 
 desc

Results in the following :-

poland 78 48 24 12 <- keep

poland 1 15 5 0 <- keep

poland 23 12 6 3

poland 2 5 0 0

poland 3 0 5 0

poland 4 0 0 5

ireland 1 9 3 0 <- keep

ireland 2 3 0 0 <- keep

ireland 3 0 3 0

ireland 4 0 0 3

france 12 24 12 6 <- keep

france 1 3 1 0 <- keep

france 231 1 0 0

france 2 1 0 0

france 4 0 0 1

france 3 0 1 0

Thanks Jon

© Stack Overflow or respective owner

Related posts about mysql

Related posts about group-by