I have two tables as below:
Table A:
| ID | Age | Dept | Salary | Start_date |
|---|---|---|---|---|
| 1 | 30 | A | $1000 | 01-01-2000 |
| 1 | 31 | B | $1200 | 01-01-2022 |
| 2 | 25 | C | $1200 | 01-06-2021 |
| 2 | 26 | A | $1300 | 01-01-2022 |
| 3 | 34 | D | $1400 | 01-01-2021 |
| 3 | 35 | C | $1800 | 01-01-2022 |
Table B:
| ID | Salary | Start_date |
|---|---|---|
| 1 | $1500 | 01-06-2022 |
| 2 | $1800 | 01-01-2022 |
| 3 | $1600 | 01-06-2021 |
I want to insert synthetic new records in Table A, when there is a mismatch in ID and start_date combination between Table A and Table B. The new record should get the Age & Dept from table A for the record which has the closest start date from the missing record in Table B, and salary and start date from table B.
Output:
| ID | Age | Dept | Salary | Start_date |
|---|---|---|---|---|
| 1 | 30 | A | $1000 | 01-01-2000 |
| 1 | 31 | B | $1200 | 01-01-2022 |
| 1 | 31 | B | $1500 | 01-06-2022 |
| 2 | 25 | C | $1200 | 01-06-2021 |
| 2 | 26 | A | $1300 | 01-01-2022 |
| 3 | 34 | D | $1400 | 01-01-2021 |
| 3 | 34 | D | $1600 | 01-06-2021 |
| 3 | 35 | C | $1500 | 01-01-2022 |
Please help to write SQL queries which will achieve this.
I am facing problems in identifying the rows from Table A which has the closest start_date from the records in Table B.
Use
UNION ALLto combine the two tables and then theLAST_VALUEanalytic function to get the most recentageanddeptvalues when they are not present:Which, for the sample data:
Outputs:
If you want to
INSERTthe missing rows then, from Oracle 12, you can use aLATERALjoin andFETCH FIRST ROW ONLYto find the most recentageanddeptvalues for each row oftable_b:fiddle