sql >> Database teknologi >  >> RDS >> Mysql

sql vælg top 5 hver måned

Prøv denne forespørgsel

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 |

  1. Trådsikkerhed af MySQL's Select Last_Insert_ID

  2. SQL Stored Procedure - variabel for kort

  3. SQL:Brug af ISNULL med dynamisk pivot

  4. Sådan viser du billeder fra databasen i JSF