I have a view where I'm trying to merge two sets of time-series data which are stored in different ways. Set D has a single value stored with every time point. Set R has values which are stored with only an effective date, and they remain in effect until superseded. Here's an example table structure:
Table D
---------+------------------+--------
D_series | D_time | D_value
---------+------------------+--------
1 | 2012-01-01 00:00 | 4.52
1 | 2012-01-01 01:00 | 2.41
1 | 2012-01-01 02:00 | 5.98
1 | 2012-01-01 03:00 | 3.51
2 | 2012-01-01 00:00 | 4.54
2 | 2012-01-01 01:00 | 6.41
2 | 2012-01-01 02:00 | 5.28
2 | 2012-01-01 03:00 | 3.11
3 | 2012-01-01 00:00 | 4.22
3 | 2012-01-01 01:00 | 9.41
3 | 2012-01-01 02:00 | 3.98
3 | 2012-01-01 03:00 | 3.53
Table L
---------+---------
D_series | R_series
---------+---------
1 | 1
2 | 1
3 | 2
Table RV
---------+----------+--------
R_series | R_header | R_value
---------+----------+--------
1 | 1 | 5.23
1 | 2 | 2.98
2 | 1 | 1.35
Table RH
---------+-----------------
R_header | R_start
---------+-----------------
1 | 2012-01-01 00:00
2 | 2012-01-01 01:49
3 | 2012-01-01 02:10
I want the view to return all points in D_time
alongside their corresponding D_value
and whatever R_value
is current:
---------+------------------+---------+--------
D_series | D_time | D_value | R_value
---------+------------------+---------+--------
1 | 2012-01-01 00:00 | 4.52 | 5.23
1 | 2012-01-01 01:00 | 2.41 | 5.23
1 | 2012-01-01 02:00 | 5.98 | 2.98
1 | 2012-01-01 03:00 | 3.51 | 2.98
2 | 2012-01-01 00:00 | 4.54 | 5.23
2 | 2012-01-01 01:00 | 6.41 | 5.23
2 | 2012-01-01 02:00 | 5.28 | 2.98
2 | 2012-01-01 03:00 | 3.11 | 2.98
3 | 2012-01-01 00:00 | 4.22 | 1.35
3 | 2012-01-01 01:00 | 9.41 | 1.35
3 | 2012-01-01 02:00 | 3.98 | 1.35
3 | 2012-01-01 03:00 | 3.53 | 1.35
I know that I can do this if I make a subquery and join to it:
select D.D_series, D_time, D_value, RV1.R_value
from D
join L on L.D_series = D.D_series
join RV RV1 on RV1.R_series = L.R_series
join RH RH1 on RH1.R_header = RV1.R_header and RH1.R_start <= D.D_time
left join (
select R_series, R_value, R_start
from RV RV2
join RH RH2 on RH2.R_header = RV2.R_header
) RZ on RZ.R_series = RV1.R_series and RZ.R_start > RH1.R_start
where RZ.R_start is null or RZ.R_start > D_time
But as I understand it, this subquery will fetch every record in RV
and RH
first, even if the view only involves a few R_series
. Is there any way to eliminate this subquery and make it into a standard join?