I have a series of records that can be grouped by a group_id
Example records:
╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║ 2 │ null │
│ 2 ║ 1 │ null │
│ 3 ║ 1 │ null │
│ 4 ║ 1 │ null │
│ 5 ║ 2 │ null │
│ 6 ║ 2 │ null │
│ 7 ║ 3 │ null │
│ 8 ║ 3 │ null │
│ 9 ║ 3 │ null │
└───╨──────────┴───────────────────┘
I want to set the position_in_group
for each record. It is the position of the record inside the group if I GROUP BY group_id
.
For example:
In the group with id 1, the record with id=2 is the first, so its position_in_group
would be 1.
The final table would be:
╭───╥──────────┬───────────────────╮
│id ║ group_id │ position_in_group │
╞═══╬══════════╪═══════════════════╡
│ 1 ║ 2 │ 1 │
│ 2 ║ 1 │ 1 │
│ 3 ║ 1 │ 2 │
│ 4 ║ 1 │ 3 │
│ 5 ║ 2 │ 2 │
│ 6 ║ 2 │ 3 │
│ 7 ║ 3 │ 1 │
│ 8 ║ 3 │ 2 │
│ 9 ║ 3 │ 3 │
└───╨──────────┴───────────────────┘
Is there any way I can do this in a SQL query?