I have two tables as below :
table 1:
ID B C D E Date
1 b c D E 2018/10/10
1 c d A B 2018/10/14
Table 2 :
ID B C Date
1 b c 2018/10/10
1 x y 2018/10/11
1 y x 2018/10/12
1 p q 2018/10/13
1 c d 2018/10/14
Table A has 6 columns, where as table 2 has 4 columns. Using left join the result is :
Select * from Table2 t2 left join table1 t1
on t2.id=t1.id and t2.Date = t1.Date
Left join result is :
ID B C D E Date1 ID B C Date2
1 b c D E 2018/10/10 1 b c 2018/10/10
- - - - - - 1 x y 2018/10/11
- - - - - - 1 y x 2018/10/12
- - - - - 1 p q 2018/10/13
1 c d A B 2018/10/14 1 c d 2018/10/14
Note :
'-' represnt NULL.
Dates are sorted in left join result -- order by table2.date , table1.date asc
- I have taken result of join in cte. not able to generate final result.
Expected Result :
ID B C D E Date
1 b c D E 2018/10/10
1 x y D E 2018/10/11
1 y x D E 2018/10/12
1 p q D E 2018/10/13
1 c d A B 2018/10/14
Where Date from table1 is null in left join result, the search for previous non null date of table 1 , which would be just less than current date of table 2.
And fetch values of column D and E from there and keep the values of column B and C from current record where Date1 is null.
Being a newbie in sql, I am stuck in this. Please help.
Thanks in advance.