(SQL SERVER 2008)
I have timestamped records in multiple tables to join to a master/base table. The timepoints are sometimes equal to the base table, but sometimes not.
Code to create tables:
create table base (time float);
create table table2 (time float, val2 char(1));
create table table3 (time float, val3 int);
insert into base values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
insert into table2 values (1, 'a'),(5, 'z'),(6, 'm'),(9, 'b');
insert into table3 values (1.5, 1),(5.3, 10),(5.5, 0),(8.1, 4);
The result set should be one row per record from the base table and the “most recent” value from the other tables. Previously, these tables were “joined” in Excel using Vlookup set to TRUE, which takes the closest-without-going-over match from a sorted table.
Final result should look like:
time | val2 | val3
1 | a | NULL
2 | a | 1
3 | a | 1
4 | a | 1
5 | z | 1
6 | m | 0
7 | m | 0
8 | m | 0
9 | b | 4
10 | b | 4
How can I replicate this with a SQL statement?
I’ll take readability over efficiency here since there are only ~100 records at play.
Perhaps the most readable are correlated subqueries in the
selectclause:I’m not generally a fan of
selectwithinselect, but the correlated subquery does mimic the behavior of the Excel vlookup.http://sqlfiddle.com/#!3/3545e/18
(Thank you Laurence for the above code and the SQL Fiddle.)
The use of
maxrequires that the values be non-decreasing. The following version works regardless:http://sqlfiddle.com/#!6/a5148/5