开发者

Selecting top 3 items per customer [duplicate]

开发者 https://www.devze.com 2023-03-20 04:30 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to select maximum 3 items per users in MySQL?
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

精彩评论

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