I have two tables, one for values, one for location, and I'm trying to interpolate the location. The tables have been simplified to the following:
CREATE TABLE value( Timestamp DATETIME2, Value float NOT NULL, PRIMARY KEY(Timestamp) ); CREATE TABLE location( Timestamp DATETIME2, Position INT NOT NULL, PRIMARY KEY(Timestamp) ); INSERT INTO value VALUES ('2011/12/1 16:55:01', 1), ('2011/12/1 16:55:02', 5), ('2011/12/1 16:55:05', 10), ('2011/12/1 16:55:08', 6); INSERT INTO location VALUES ('2011/12/1 16:55:00', 0), ('2011/12/1 16:55:05', 10), ('2011/12/1 16:55:10', 5)
Expected results:
TimeStamp, Value, LowerTime, LowerLocation, UpperTime, UpperLocation 2011-12-01 16:55:01, 1, 2011-12-01 16:55:00, 0, 2011-12-01 16:55:05, 10 2011-12-01 16:55:02, 5, 2011-12-01 16:55:00, 0, 2011-12-01 16:55:05, 10 2011-12-01 16:55:05, 10, 2011-12-01 16:55:05, 10, 2011-12-01 16:55:05, 10 2011-12-01 16:55:08, 6, 2011-12-01 16:55:05, 10, 2011-12-01 16:55:10, 5
(Keep in mind that these are simplified data examples to get an idea of ββthe query I'm trying to execute.)
To do the interpolation, I need to find out the time and places before and after the given time values. I am currently doing this with a query that looks like this:
SELECT V.Timestamp, V.Value, (SELECT MAX(Timestamp) FROM dbo.location WHERE Timestamp <= V.Timestamp) as LowerTime, (SELECT TOP 1 Position FROM dbo.location WHERE Timestamp <= V.Timestamp ORDER BY timestamp DESC) as LowerLocation, (SELECT MIN(Timestamp) FROM dbo.location WHERE Timestamp >= V.Timestamp) as UpperTime, (SELECT TOP 1 Position FROM dbo.location WHERE Timestamp >= V.Timestamp ORDER BY timestamp ASC) as UpperLocation FROM dbo.value V
Now it works, but it obviously does a lot of work. I think there should be a simplification of the request that I miss, but I played with it all morning and did not come up with anything concrete. Hope someone has a better idea.
I'm currently studying whether there is a way to calculate the LowerTime and UpperTime values ββand use them when determining locations. Sort of:
SELECT V.Timestamp, V.Value, (SELECT MAX(Timestamp) FROM dbo.location WHERE Timestamp <= V.Timestamp) as LowerTime, (SELECT Position FROM dbo.location WHERE Timestamp = LowerTime) as LowerLocation, (SELECT MIN(Timestamp) FROM dbo.location WHERE Timestamp >= V.Timestamp) as UpperTime, (SELECT Position FROM dbo.location WHERE Timestamp = UpperTime) as UpperLocation FROM dbo.value V
but it does not work.
EDIT1: Updated request as suggested. However, no visible changes in runtime.
EDIT2: Added my thoughts on the approach I'm trying to do now.