每个项目价值增加一

Increment value by one for each project

我想更改 Version 列的值并将其从“0”填充为按 Project_ID[=30= 递增的值] 并按 CreatedDate 排序。这将在 Oracle 中,它适用于现有行,而不是 auto_increment 插入。

之前

Project_ID Version CreatedDate
1 0 Jun-1-2011
2 0 Jun-1-2011
1 0 Jun-2-2011
2 0 Jun-2-2011
1 0 Jun-3-2011
2 0 Jun-3-2011
3 0 Jun-4-2011
1 0 Jun-4-2011

希望的结果

Project_ID Version CreatedDate
1 1 Jun-1-2011
2 1 June-1-2011
1 2 Jun-2-2011
2 2 Jun-2-2011
1 3 Jun-3-2011
2 3 Jun-3-2011
3 1 Jun-4-2011
1 4 Jun-4-2011

还没有尝试过任何东西,如果我要做一个简单的

UPDATE table_name SET version = version+1  GROUP BY project_id 

我认为这行不通

您可以为此使用解析函数row_number()over(partition by Project_ID order by created_date)。很遗憾,您不能在

中使用解析函数
update (select ...,analytic_function()... from t) 
set val=new_val

但是您可以为此使用 merge 语句:

merge into t 
using (
    select rowid rid, row_number()over(partition by Project_ID order by created_date) new_value
    from t
    ) new_t
on (t.rowid = new_t.rid)
when matched then 
update set Version = new_value;

DBFiddle: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=e778bb0b43e6fcc0ce6961d3a7887cd6

如果某些列具有唯一值,则可以在没有 row_number 的情况下完成。

所以假设没有主键,并且有一个 Created_Date 具有唯一的时间值。

update yourtable t
set Version = (
  select count(*)
  from yourtable t2
  where t2.Project_ID = t.Project_ID
    and t2.Created_Date <= t.Created_Date
);

8 行受影响

select * from yourtable
ID | PROJECT_ID | VERSION | CREATED_DATE
-: | ---------: | ------: | :-----------
 1 |          1 |       1 | 18-AUG-21   
 2 |          2 |       1 | 19-AUG-21   
 3 |          1 |       2 | 20-AUG-21   
 4 |          2 |       2 | 21-AUG-21   
 5 |          1 |       3 | 22-AUG-21   
 6 |          2 |       3 | 23-AUG-21   
 7 |          3 |       1 | 24-AUG-21   
 8 |          1 |       4 | 25-AUG-21   

db<>fiddle here