I have the following table:
X_ID X_NAME X_TYPE X_SORT_ID
10 BOOK 1 NULL
20 PEN 1 NULL
30 WATCH 2 NULL
5 TENT 3 NULL
What I'm trying to achieve is to populate the X_SORT_ID column with incremented values starting with 1 based on value in X_ID. So the table would look like this:
X_ID X_NAME X_TYPE X_SORT_ID
10 BOOK 1 2
20 PEN 1 3
30 WATCH 2 4
5 TENT 3 1
I need to update this table only for all existing rows. The records that will be added in the future will use a sequence that would set the X_SORT_ID field to the next value.
The only query I came up with is not exactly what I need.
UPDATE X_ITEMS
SET X_SORT_ID = (SELECT MAX(X_ID) FROM X_ITEMS) + ROWNUM
WHERE X_SORT_ID IS NULL;
I could use just a rownum, but this would assign value of 4 to the last record with X_ID = 5, which is not what I wanted.
I'd be thankful for any suggestions.