I am trying to join two tables in a manner very similar to an "as of" join, except instead of choosing the row with the last timestamp to join onto (assuming they are sorted in time order), I want to join with the closest timestamp. For example:
q)t: ([]time:10:00:06 10:00:03 10:00:04;sym:`msft`ibm`ge;qty:100 200 150)
q)t
time sym qty
-----------------
10:00:06 msft 100
10:00:03 ibm 200
10:00:04 ge 150
q)q: ([]time:10:00:00 10:00:00 10:00:02 10:00:07 10:02:00;sym:`ibm`msft`msft`msft`ibm;px:100 99 101 102 98 )
q)q
time sym px
-----------------
10:00:00 ibm 100
10:00:00 msft 99
10:00:02 msft 101
10:00:07 msft 102
10:02:00 ibm 98
Standard as-of join:
q)aj[`sym`time;t;q]
time sym qty px
---------------------
10:00:06 msft 100 101 //10:00:02 is closest timestamp that is not greater than 10:00:06, so that px is chosen
10:00:03 ibm 200 100
10:00:04 ge 150
The thing is, for msft, since 10:00:07 is closer than 10:00:02 to the original microsoft timestamp, even though it's greater than the original msft timestamp, what I want ideally is is:
q)closest_join[`sym`time;t;q]
time sym qty px
---------------------
10:00:06 msft 100 102 //10:00:07 is +1second, 10:00:02 is -6second, so I want it to use 10:00:07
10:00:03 ibm 200 100
10:00:04 ge 150
How would you do this? Note it must work for multiple "msft" rows in the source table similar to how aj does.