Row number per group in mysql

前端 未结 6 563
臣服心动
臣服心动 2020-11-27 17:27

I want to produce query result base on this scenario that can create row number according to crew_id and type.

id   crew_id   amount    type
 1      4                


        
6条回答
  •  青春惊慌失措
    2020-11-27 18:10

    @Janty's answer does not work when the type starts with a number (the rank starts at 2 instead of 1).

    Use the following instead:

    SELECT id,
         crew_id,
         amount,
         CASE type 
             WHEN @curType THEN @curRow := @curRow + 1 
             ELSE @curRow := 1
         END AS rank,
         @curType := type AS type
    FROM Table1 p
    JOIN (SELECT @curRow := 0, @curType := '') r
    ORDER BY crew_id, type
    

提交回复
热议问题