0

I have Customer_Record table with following columns

customer_id | item_id | item_count
1            2           10
1            3           9
1            4           2
1            5           2
2            2           5
2            4           1
2            8           2
4            1           2            
4            5           3
4            8           7

Now i want to get top 2 items (items_id) of each customer on the basis of item_count. Please help me to figure out this .

Result like:-

customer_id | item_id | item_count
1            2           10
1            3           9
2            2           5
2            4           1
4            1           2            
2
  • I don't understand how the result set relates to the requirement ?!?
    – Strawberry
    Aug 17, 2014 at 8:32
  • ...and what about ties?
    – Strawberry
    Aug 17, 2014 at 8:49

1 Answer 1

1

For mysql you can use rank query to get top results per group

SELECT t.customer_id,
t.item_id,
t.item_count
FROM (
SELECT t.*,
@rank:= CASE WHEN @group = t.customer_id THEN @rank +1 ELSE 1 END rank ,
@group:= t.customer_id 
 FROM
t
JOIN (SELECT @group:='',@rank:='') t1
ORDER BY t.customer_id ,item_count  DESC
) t WHERE t.rank <=2

Fiddle Demo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.