Skip to content
Advertisement

If Row from left joined table is null use another row

I have two table that I am trying to join(see below). Each have the same four columns on which I need to join. The second is the complete list, while the first may be missing some records.

Where the records are missing I want to use the lowest ROWNUM that matches the other three. I am failing to see a way through the woods on this one.

This returns:

enter image description here

I am trying to get T1 in Line 2, T2 in line 4 and T5 in line 8.

As you can see with TAX_YEAR 2020 sometimes there is info that needs to match on the ROWNUM that is different, so I cannot remove the AND TT.ROWNUM = OC.ROWNUM

Advertisement

Answer

If I understand you correctly, a lateral join (or a subquery) with an inequality condition does what you want:

Basically the lateral join searches for an exact match, and falls back on the first match in smaller rownums.

Demo on DB Fiddle:

seg_id | accountno | impno | tax_year | occ_code
-----: | :-------- | ----: | -------: | :-------
     1 | A1        |     1 |     2018 | T1      
     5 | A1        |     1 |     2018 | T1      
     2 | A1        |     1 |     2019 | T2      
     6 | A1        |     1 |     2019 | T2      
     3 | A1        |     1 |     2020 | T3      
     7 | A1        |     1 |     2020 | T4      
     4 | A1        |     1 |     2021 | T5      
     8 | A1        |     1 |     2021 | T5      
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement