Skip to content
Advertisement

left join on the first appeared row by datetime

If classes ‘Math’ or ‘Biology’ have flag is NULL or = 0, we need to left join with the first appeared (according to the date) classes ‘Literature’ or ‘English Literature’ from the below.

If classes ‘Math’ or ‘Biology’ have flag = 1 then we need to left join with the most recent (according to the date) classes ‘Literature’ or ‘English Literature’

Initial table:

Result table (contain class without class = ‘Literature’, ‘English Literature’):

Explanations:

  1. Biology at 2020-09-19 13:18:00.000 doesn’t have a join because it has flag NULL and below (later than ‘Biology’) there are no rows with ‘Literature’ and ‘English Literature’ according to the rules.
  2. Biology at 2020-07-07 21:08:00.000 with flag 1 also doesn’t have a join because there was no ‘ English Literature‘ or ‘ Literature‘ before

3) Math at 2020-07-07 20:08:00.000 with flag 0 (it is the first row) . As the flag is 0 so we look at the first appeared ‘Literature’ or ‘English Literature’ class after this class. The first appeared is ‘Literature’ at 2020-07-15 20:08:00.000 so we match them

How to do LEFT JOIN with finding recent or first row according to the date?

Advertisement

Answer

Without claiming that it is the most elegant solution; this would work:

You have some blank flag values, I assumed NULL, You have not indicated which database products you used, I assumed SqlServer (but it should work with majority of them).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement