sql >> Base de Datos >  >> RDS >> Mysql

sql seleccione los 5 mejores cada mes

Prueba esta consulta

select * from
(select 
@rn:=if(@prv=product_id, @rn+1, 1) as rId,
@prv:=product_id as product_id,
year, 
month,
revenue
from tbl
join
(select @prv:=0, @rn:=0)tmp
order by 
product_id, revenue desc) a
where rid<=5

SQL FIDDLE :

| RID | PRODUCT_ID | YEAR | MONTH | REVENUE |
---------------------------------------------
|   1 |          1 | 2013 |     1 |     100 |
|   2 |          1 | 2013 |     1 |      90 |
|   3 |          1 | 2013 |     1 |      70 |
|   4 |          1 | 2013 |     1 |      60 |
|   5 |          1 | 2013 |     1 |      50 |
|   1 |          2 | 2013 |     1 |    5550 |
|   2 |          2 | 2013 |     1 |     550 |
|   3 |          2 | 2013 |     1 |     520 |
|   4 |          2 | 2013 |     1 |     510 |
|   5 |          2 | 2013 |     1 |     150 |