2014-02-26 65 views
0

我有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 

我我喜歡加入他們,這樣我的日日期就在第一列,然後是最近的拆分和拆分因子的日期,直到日期日期=拆分日期(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

你用什麼RDBMS? –

+0

MS-SQL Server 2008 R2 –

回答

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 
    ) 

上裂開的內加入限制了可分開行與同fs_perm_sec_id必然也會,而其中的限制可分開行進一步只有那些split_date最高的是< =連續表上的日期。

效率將取決於splitTable上的索引和每個行中的行數。猜測,這將有助於在(fs_perm_sec_id,split_date)的splitTable上創建一個索引,但是您必須嘗試並查看查詢計劃來檢查它。 (SSMS在SQL Server與建議索引可以幫助提高查詢時間非常有幫助。)

+0

完美,謝謝西蒙。這很好。 –

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