I have basically one table but I have created another(subset) table from the original one. I'll original table as Table 1
and subset table as Table 2
.
Table_1
looks like this:
Table_2
looks like this:
Final_table
needs to look like this:
Now as you can see, Table_2
has been created by picking certain texts out of Table_1
. Now what I really need is a way to first look up these exact same rows of data in Table_1
, and then for each row looking backwards using date (timestamp) find a row when value2
from Table_2
matches with text from Table_1
. Whenever it does, get the value and add it to value_original
column.
Final
table shows the result I need to get. How do I do that using Vertica sql?
I have tried this code:
SELECT *
FROM
(SELECT table_2.*, table_1.value as value_original
FROM
(Select * from table
where date < '1/10/2020'
and text = 'settle') as table_2
LEFT JOIN
(Select * from table where date < '1/10/2020') as table_1
ON table_2.id1 = table_1.id1 and table_2.id2 = table_1.id2 and table_2.value2 = table_1.text) as final_table
where value_original is not null
ORDER BY date
I didn't realize how terrible my choice of aliases were until now, sorry about that. After trying this code, I ended up in situations where it would have exact same values multiple times in Table_1 but I need the one that is closest to the selected row in Table_2 going backwards using date (timestamp). I'm not sure how to do that. Any suggestions?
Thanks!