SQL Server使用单日期列查找日期范围内的记录
问题描述:
我有一个带有生效日期字段的表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*
的事情是,有可能不是 “结束” 有效日期。所以我也需要考虑这种可能性。任何想法都非常感谢。
答
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;
这不会返回11.75吗?这不是OP想要的。我认为你的意思是小于或等于内部选择。 –
翻转我的箭头。谢谢! – SqlZim
谢谢!这就是它。 – RiSt