简体   繁体   中英

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. 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.

- 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:

- 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? Do you guys think that I can use a different approach to reach my target?

You could use LAG with UPDATE directly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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