views:

25

answers:

1

I have a table with these columns

create table demo (
    ID integer not null,
    INDEX integer not null,
    DATA varchar2(10)
)

Example data:

ID  INDEX DATA
1   1     A
1   3     B
2   1     C
2   1     D
2   5     E

I want:

ID  INDEX DATA
1   1     A
1   2     B            -- 3 -> 2
2   1     C or D       -- 1 -> 1 or 2
2   2     D or C       -- 1 -> 2 or 1
2   3     E            -- 5 -> 3 (closing the gap)

Is there a way to renumber the INDEX per ID using a single SQL update? Note that the order of items should be preserved (i.e. the item "E" should still be after the items "C" and "D" but the order of "C" and "D" doesn't really matter.

The goal is to be able to create a primary key over ID and INDEX.

If that matters, I'm on Oracle 10g.

+1  A: 
MERGE
INTO    demo d
USING   (
        SELECT  rowid AS rid, ROW_NUMBER() OVER (PARTITION BY id ORDER BY index) AS rn
        FROM    demo
        ) d2
ON      (d.rowid = d2.rid)
WHEN MATCHED THEN
UPDATE
SET     index = rn
Quassnoi
A well deserved 25 points! Thank you!
Aaron Digulla