MySQL - Get a counter for each duplicate value

后端 未结 4 779
时光说笑
时光说笑 2020-12-10 13:08

I have a table with two columns.

+------+------+
| data | num  | 
+------+------+
| a    |      | 
| a    |      |
| a    |      |
| b    |      |
| b    |            


        
4条回答
  •  星月不相逢
    2020-12-10 13:57

    Here is a simple query that will do what you want.

    select id,data,rownum 
      from (
              select id,
                     data,
                     @row:=if(@prev=data,@row,0) + 1 as rownum,
                     @prev:=data 
                from tbl
            order by data,id
    )t
    

    I have included an id on each row. But you don't need it.

    Go fiddle: http://sqlfiddle.com/#!2/1d1f3/11/0

    Credit: Want Row Number on Group of column in MY SQL?

提交回复
热议问题