Selecting top 3 items per customer [duplicate]
Possible Duplicate:
How to select maximum 3 items per users in MySQL?
I have an sql table with 3 columns: CustomerNumber, Item, Count
There are about 125 items in this table; each row contains the customer number the item number and the number of times that customer has bought it.
开发者_如何转开发I'd like to have a query with each customer and their top 3 items. How would I go about doing this?
set @i := 0;
set @cn = -1;
select CustomerNumber, Item, `Count`
from (
select CustomerNumber, Item, `Count`,
case when CustomerNumber != @cn then @i := 0 else @i := @i + 1 end as i,
@cn := CustomerNumber
from t
order by CustomerNumber, `Count` desc
) ss
where i < 3
精彩评论