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:>
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.