我有一个视图,我正在尝试合并两组以不同方式存储的时间序列数据。设置 D 在每个时间点都有存储的单个值。设置 R 的值只存储生效日期,< / em>并且它们一直有效直到被取代。这是一个示例表结构:
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
我希望该视图返回D_time
中所有与其对应的D_value
以及当前R_value
无关的点:
---------+------------------+---------+--------
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
我知道如果我创建一个子查询并加入它,我就能做到这一点:
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
但据我了解,此子查询将首先在RV
和RH
中获取每个记录,即使该视图仅涉及少量R_series
。有没有办法消除这个子查询并使其成为标准连接?
答案 0 :(得分:0)
您是否考虑过使用交叉申请?他们在没有简单连接条件的情况下表现良好。
请参阅此答案:When should I use Cross Apply over Inner Join?
在你的情况下,我认为这些方面可能有用:
select D.D_series, D_time, D_value, current_r_values.R_value
from D
join L on L.D_series = D.D_series
cross apply (
select top 1 R_series, R_value, R_start
from RV RV2
join RH RH2 on RH2.R_header = RV2.R_header
where RH2.R_Start<D.D_time
and RV2.R_series = L.R_series
order by R.R_Start DESC) current_r_values
我知道这并不是你想要的,但我经常发现使用交叉应用可能比加入不等式要快得多。