我有2张桌子,每张桌子有连续的每日日期/价格:
fs_perm_sec_id date p_price
KX8CBL-S-GB 2014-02-21 3.3515
KX8CBL-S-GB 2014-02-20 3.345
KX8CBL-S-GB 2014-02-19 3.3575
KX8CBL-S-GB 2014-02-18 3.297
和另一个偶发日期条目:
fs_perm_sec_id split_date p_split_factor
KX8CBL-S-GB 1998-07-06 0.333333015
KX8CBL-S-GB 1991-02-04 0.970365703
KX8CBL-S-GB 1987-07-06 0.333333015
KX8CBL-S-GB 1985-05-03 0.983739793
我想加入他们,以便我在第1列中有每日日期,然后是最近拆分和拆分因子的日期,直到每日日期=拆分日期(1998-07-06) ),然后让它返回下一个分割日期(1991-02-04),直到每日价格日期达到......等等。
所以:
Date Split_Date Split_factor
2014-02-21 1998-07-06 0.333333015
2014-02-20 1998-07-06 0.333333015
2014-02-19 1998-07-06 0.333333015
...
1998-07-06 1998-07-06 0.333333015
1998-07-05 1991-02-04 0.970365703
1998-07-04 1991-02-04 0.970365703
...
答案 0 :(得分:0)
这样的事情应该做:
select *
from continuousTable c
inner join splitTable s on s.fs_perm_sec_id = c.fs_perm_sec_id
where s.split_date =
(
select max(s2.split_date)
from splitTable s2
where s2.fs_perm_sec_id = c.fs_perm_sec_id
and s2.split_date <= c.date
)
splitTable上的内部联接将splitTable行限制为具有相同fs_perm_sec_id的值,而where限制splitTable行仅限于具有split_date的行,该值最大为&lt; =连续表上的日期。
效率取决于splitTable上的索引以及每个索引中的行数。猜测,它有助于在splitTable上有一个索引(fs_perm_sec_id,split_date),但你必须试验并查看查询计划来检查它。 (SQL Server中的SSMS非常有助于建议可以帮助缩短查询时间的索引。)
答案 1 :(得分:0)
尝试非等值连接,然后根据split_date选择最新的候选者:
with crossdata as (
select p.fs_perm_sec_id
, p.[date]
, p.p_price
, s.p_split_factor
, s.split_date
, ROW_NUMBER() over (partition by p.fs_perm_sec_id, p.[date] order by s.split_date desc) cand from #price p
join #split s
on p.[date] >= s.split_date
and p.fs_perm_sec_id = s.fs_perm_sec_id
)
select fs_perm_sec_id
, split_date
, p_price
, p_split_factor
from crossdata
where cand = 1