2016-11-28 94 views
0

我有一個帶有生效日期字段的表A,需要確定另一個表B中的字段落在一個生效日期和下一個生效日期範圍之間(用於用於在表B中分配不同字段的值)。例如。SQL Server使用單日期列查找日期範圍內的記錄

A 

[Effective Date] [Cost] 
---------------- ----------------  
1/1/2016   10.25 
5/20/2016   11.75 
B 

[Service Date]  [Cost] 
---------------- ---------------- 
3/1/2016   *should be 10.25* 

的事情是,有可能不是 「結束」 有效日期。所以我也需要考慮這種可能性。任何想法都非常感謝。

回答

0
select 
    b.[Service Date] 
    , Cost = (select top 1 a.Cost 
       from a 
       where a.[Effective Date] <= b.[Service Date] 
       /* assuming there are other important correlating identifiers, 
        you would add something like: */ 
       -- and a.[ServiceId] = b.[ServiceId] 
       order by a.[Effective Date] desc 
      ) 
from b; 
+1

這不會返回11.75嗎?這不是OP想要的。我認爲你的意思是小於或等於內部選擇。 –

+0

翻轉我的箭頭。謝謝! – SqlZim

+0

謝謝!這就是它。 – RiSt

相關問題