Whatever the data available in previous record it should add to the new record

50 Views Asked by At

Thanks in advance for answer my question. Assume I have a table like t1. There are 3 columns in the table.

t1.id       t1.ins_dt           base_id
10000       2024-03-27 00:00:00 1234/45678/000/00
10000       2024-03-27 06:30:00 1234/45678/001/00
10000       2024-03-27 09:30:00 1234/45678/002/00

I have another table like t2.

t2.id    t2.ins_dt              t2.cv
10000    2024-03-27 00:00:00    OD
10000    2024-03-27 00:00:00    TP
10000    2024-03-27 06:30:00    PA

If I join these two tables I want the output like,

t1.id     t1.base_id           t2.cv
10000     1234/45678/000/00    OD
10000     1234/45678/000/00    TP
10000     1234/45678/001/00    OD
10000     1234/45678/001/00    TP
10000     1234/45678/001/00    PA
10000     1234/45678/002/00    OD
10000     1234/45678/002/00    TP
10000     1234/45678/002/00    PA
2

There are 2 best solutions below

0
Error_2646 On

Just inferring from the sample data. Join t1 to t2 on id, for each t2.ins_dt on or earlier than t1.ins_dt.

Fiddle: https://dbfiddle.uk/It5hFkbh

select t1.id,
       t1.base_id,
       t2.cv
  from t1
 inner
  join t2
    on t1.id = t2.id
   and t1.ins_dt >= t2.ins_dt
 order
    by t1.ins_dt,
       t2.cv;
0
tahzibi.jafar On
select   t1.id, t1.base_id, t2.cv
from     t1, t2
where    t1.id = t2.id
     and t1.ins_dt >= t2.ins_dt
order by t1.ins_dt, t2.cv;