简体   繁体   English

Oracle数据库:如何更新函数结果?

[英]Oracle db: How to update with the results of a function?

I have a table that looks like this one: 我有一张看起来像这样的桌子:

id1 | id2 | start_date | end_data

where id1, id2 and start_data shape the primary key. 其中id1,id2和start_data构成主键。 Bellow you can see an example: 在下面您可以看到一个示例:

- 5624 |    JK  |   16/06/2017  |   20/06/2017
- 5624 |    JK  |   20/06/2017  |   22/06/2017
- 5624 |    JK  |   27/09/2017  |   01/10/2017
- 5624 |    JK  |   09/10/2017  |   (null)
- . . .

So I want to update the start_date with the value of end_data of the previous column. 所以我想用上一列的end_data值更新start_date。

- 5624 |    JK  |   16/06/2017  |   20/06/2017
- 5624 |    JK  |   20/06/2017  |   22/06/2017
- 5624 |    JK  |   22/06/2017  |   01/10/2017
- 5624 |    JK  |   01/10/2017  |   (null)
- . . .

I will delete the primary key temporarily. 我将暂时删除主键。

I try to use the LAG function and I get: 我尝试使用LAG函数,并且得到:

- id1 | id2 | start_date | end_data | LAG
__________________________________________
- 5624 |    JK  |   16/06/2017  |   20/06/2017 | (null)
- 5624 |    JK  |   20/06/2017  |   22/06/2017 | 20/06/2017
- 5624 |    JK  |   27/09/2017  |   01/10/2017 | 22/06/2017
- 5624 |    JK  |   02/10/2017  |   (null)     | 01/10/2017 
- . . .

How can I use the result of LAG function to update every row with his value in start_date column? 如何使用LAG函数的结果用start_date列中的值更新每一行? Do you guys think that I can use a different approach to reach my target? 你们认为我可以使用其他方法来达到目标​​吗?

You could use LAG with UPDATE directly: 您可以将LAGUPDATE直接一起使用:

UPDATE t
SET START_DATE = 
   (SELECT nws
    FROM (SELECT rowid, COALESCE(LAG(END_DATA)
          OVER(PARTITION BY ID1, ID2 ORDER BY END_DATA ASC), START_DATE) AS nws
          FROM t) s 
    WHERE s.rowid = t.rowid);

DBFiddle Demo DBFiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM