SQLite Forum

Nearest-match join
Login
Example:

```
create table t1 (id integer primary key, ts real not null, a, b, c);
create table t2 (id integer primary key, ts real not null, d, e, f);

with nboe_id(id1, id2) -- find the Next Before or Equal keyset
  as (
      select t1.id as id1,
             (
                 select t2.id
                   from t2
                  where t2.ts <= t1.ts
               order by t2.ts desc
                  limit 1
             )
        from t1
     ),
     naoe_id(id1, id2) -- find the Next After or Equal keyset
  as (
      select t1.id as id1,
             (
                select t2.id
                  from t2
                 where t2.ts >= t1.ts
              order by t2.ts
                 limit 1
             )
        from t1
     ),
     keyset_ts(id1, id2) -- combine the next before and next after keysets
  as (
          select id1,
                 id2
            from nboe_id
           where id2 is not null
       union all
          select id1,
                 id2
            from naoe_id
           where id2 is not null
        order by id1
     ),
     keyset(id1, id2, mintsd) -- generate the keyset with the minimum distance
  as (
        select id1,
               id2,
               min(abs(t1.ts - t2.ts))
          from keyset_ts, t1, t2
         where id1 == t1.id
           and id2 == t2.id
      group by id1
     )
select t1.*,
       t2.*
  from keyset, t1, t2
 where id1 == t1.id
   and id2 == t2.id
;
```

NB: Not tested and I think I got the next before or equal and next after or equal order by's right.

NBB:  Added slight optimizations