Skip to content
Advertisement

How to join two tables with same date but different time such that the closest time is chosen?

I am trying to left join a Notes table where the user would upload Notes on certain time of each day onto a Score table with a date and time. The dates need to be the same, but I need to choose match each time in Notes with the closest less-than/equal to time in the Scores table. Here is an example of what to expect:

Notes Table

Scores Table

Results Table

Advertisement

Answer

Well, given that the dates are the same, the explosion of data might not be that bad. So do a join and then filter using window functions:

select sn.*
from (select s.*, n.n,
             row_number() over (partition by s.date, s.time order by n.time desc) as seqnum
      from scores s left join
           notes n
           on s.date = n.date and s.time >= n.time
     ) sn
where seqnum = 1;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement