Hi everyone,
I'm fairly new to sql and was hoping that someone can help me with an update query. I have a users table with group_id (foreign key), user_id and user_index columns. There are multiple users corresponding to each individual group_id, and user_id is a serial column which goes from 1 to the table size.
I'm looking for a query that will update the user_index column so that, for each group_id, each user will have a unique, sequential index starting with 1. So within group 1 there would be user_index 1,2,3... and within group 2 there would be user_index 1,2,3... and so on. Here is an example to clarify:
Initial state:
user_id | group_id | user_index
1 1 0
2 1 0
3 1 0
4 2 0
5 3 0
6 3 0
Desired state:
user_id | group_id | user_index
1 1 1
2 1 2
3 1 3
4 2 1
5 3 1
6 3 2
I hope that's clear. This would be easy to do in C or C++, but I'm wondering if there's a way to do it in sql.