SQLite Forum

Join tables by nearest older date
Login
One would presume that you have "other fields" in WinEvents and GameEvents that you want to be able to access.  So here is (one possible) solution.

Firstly, you need to generate the list of matches, and then retrieve the data.  So you can find the matching keys as follows:

```
select WinID,
       (
          select GameID
            from GameEvents
           where GameDate <= WinDate
        order by GameDate desc
           limit 1
       ) as GameID
  from WinEvents
;
```

which will give you all the WinID's and their corresponding GameID.  Now you want to be able to access all "joined" rows.  There are multiple ways to do that:

```
with jt(WinID, GameID)
  as (
      select WinID,
             (
                select GameID
                  from GameEvents
                 where GameDate <= WinDate
              order by GameDate desc
                 limit 1
             ) as GameID
        from WinEvents
     )
select WinEvents.*, GameEvents.*
  from jt
  join WinEvents
    on jt.WinID == WinEvents.WinID
  join GameEvents
    on jt.GameID == GameEvents.GameID
;
```

or as same thing but without using the CTE syntactic sugar,

```
select WinEvents.*, GameEvents.*
  from (
        select WinID,
               (
                  select GameID
                    from GameEvents
                   where GameDate <= WinDate
                order by GameDate desc
                   limit 1
               ) as GameID
          from WinEvents
         ) as jt
  join WinEvents
    on jt.WinID == WinEvents.WinID
  join GameEvents
    on jt.GameID == GameEvents.GameID
;
```

Note that you will likely want an index on GameDate ...