MySQL - Get a counter for each duplicate value

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

I have a table with two columns.

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


        
4条回答
  •  暖寄归人
    2020-12-10 13:32

    Unfortunately, MySQL does not have windowing functions which is what you will need. So you will have to use something like this:

    Final Query

    select data, group_row_number, overall_row_num
    from
    (
      select data,
            @num := if(@data = `data`, @num + 1, 1) as group_row_number,
            @data := `data` as dummy, overall_row_num
      from
      (
        select data, @rn:=@rn+1 overall_row_num
        from yourtable, (SELECT @rn:=0) r
      ) x
      order by data, overall_row_num
    ) x
    order by overall_row_num
    

    see SQL Fiddle with Demo

    Explanation:

    First, inner select, this applies a mock row_number to all of the records in your table (See SQL Fiddle with Demo):

    select data, @rn:=@rn+1 overall_row_num
    from yourtable, (SELECT @rn:=0) r
    

    Second part of the query, compares each row in your table to the next one to see if it has the same value, if it doesn't then start the group_row_number over (see SQL Fiddle with Demo):

    select data,
          @num := if(@data = `data`, @num + 1, 1) as group_row_number,
          @data := `data` as dummy, overall_row_num
    from
    (
      select data, @rn:=@rn+1 overall_row_num
      from yourtable, (SELECT @rn:=0) r
    ) x
    order by data, overall_row_num
    

    The last select, returns the values you want and places them back in the order you requested:

    select data, group_row_number, overall_row_num
    from
    (
      select data,
            @num := if(@data = `data`, @num + 1, 1) as group_row_number,
            @data := `data` as dummy, overall_row_num
      from
      (
        select data, @rn:=@rn+1 overall_row_num
        from yourtable, (SELECT @rn:=0) r
      ) x
      order by data, overall_row_num
    ) x
    order by overall_row_num
    

提交回复
热议问题