Skip to content
Advertisement

Join two tables where table A has a date value and needs to find the next date in B below the date in A

I got this table “A”:

and this table “B”:

Now I am looking for a way to JOIN those two tables having the “value” column in “B” mapped to the dates in “A”. The tricky part for me here is that table “B” only stores the change date and the new value. Now when I need this value in table “A” the SQL needs to look back what date is the next below the date it is asking the value for.

So in the end the JOIN of those tables should look like this:

How can I do this?

Advertisement

Answer

What we’re doing:

  • for each date in the id_date table (your table A),
  • we find the date in the date_val table (your table B)
  • which is the highest date in the date_val table (but still smaller than the id_date.date)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement