MySQL - Counter within group

后端 未结 1 705
遇见更好的自我
遇见更好的自我 2021-01-16 05:07

I would like to add a counter for each row within a group according an ascending variable. I have a solution but it does not work if some variable within groups are equal:

1条回答
  •  再見小時候
    2021-01-16 05:41

    User Defined Variables become handy when solving this issues. This should work:

    select g, x, counter from (
        select g, x,
            @counter := if (g = @prev_g, @counter + 1, 1) counter,
            @prev_g := g
        from tb, (select @counter := 0, @prev_g := null) init
        order by g, x
    ) s
    

    If you don't really mind the fourth column then you could safely remove the outer select. That would improve performance a lot.

    0 讨论(0)
提交回复
热议问题