I have the postgres table user_team which has columns user_pk, team, exercise, assigned_at and I want to auto-populate the order column with sequence of incrementing integers but only for unique pairs of user_pk and team and ordered by assigned_at:
so the column which I have is:
| user_pk | team | exercise_pk | assigned_at |
|-------------------------------------------------------------|
| 111 | blue | "exercise" | 2022-03-01 |
| 111 | blue | "exercise" | 2022-03-02 |
| 222 | blue | "exercise" | 2022-03-01 |
| 222 | blue | "exercise" | 2022-03-02 |
| 222 | blue | "exercise" | 2022-03-03 |
| 111 | green | "exercise" | 2022-03-01 |
| 111 | green | "exercise" | 2022-03-02 |
| 111 | green | "exercise" | 2022-03-03 |
| 333 | green | "exercise" | 2022-03-01 |
| 333 | green | "exercise" | 2022-03-02 |
and I want to have
| user_pk | team | exercise_pk | assigned_at | order|
|--------------------------------------------------------------------|
| 111 | blue | "exercise" | 2022-03-01 |1 |
| 111 | blue | "exercise" | 2022-03-02 |2 |
| 222 | blue | "exercise" | 2022-03-01 |1 |
| 222 | blue | "exercise" | 2022-03-02 |2 |
| 222 | blue | "exercise" | 2022-03-03 |3 |
| 111 | green | "exercise" | 2022-03-01 |1 |
| 111 | green | "exercise" | 2022-03-02 |2 |
| 111 | green | "exercise" | 2022-03-03 |3 |
| 333 | green | "exercise" | 2022-03-01 |1 |
| 333 | green | "exercise" | 2022-03-02 |2 |
Is there any way to do that in one query?
I tried with DISTINCT user_pk, team and with answer from: Updating postgres column with sequence of integers :
update bar b
set id = b2.new_id
from (select b.*, row_number() over (order by id) as new_id
from bar
) b2;
where b.pk = b2.pk;
But still cannot figure it out