开发者

Selecting top 3 items per customer [duplicate]

This question already has answers here: Closed 11 years ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜