MySQL - Get a counter for each duplicate value

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

I have a table with two columns.

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


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 13:41

    Does the data have to stay in the order shown, or can we sort by the 'data' value?

    If you can sort, then you only have to keep track of the current 'data' value, which can be done with variables:

    set @last_data = null;
    set @count = 0;
    select data, @count,
      case when @last_data is null or data != @last_data then @count := 1 else @count := @count + 1 end as new_count,
      @last_data := data, @count
    from t20120917
    order by data;
    

    If not, I think it'll be more complex...

提交回复
热议问题