我有两张桌子: 1-设置
EffectiveDate || Value
==============================
'2000-01-01' || 2
'2005-01-01' || 4
'2010-01-01' || 6
2- DataTable
ID || RecordDate
===============================
1 || '2001-01-01'
2 || '2002-01-01'
3 || '2003-01-01'
4 || '2007-01-01'
5 || '2008-01-01'
6 || '2011-01-01'
7 || '2013-01-01'
8 || '2014-01-01'
这两个表格之间的关系是来自EffectiveDate
的{{1}} Settings most be smaller(and/or equal) than RecordDate
,但必须是最新的。{1}}。
例如,结果必须是这样的:
DataTable
谢谢你的帮助:D
答案 0 :(得分:3)
您可以使用CROSS APPLY
和TOP
来获得所需的结果:
SELECT
dt.ID, dt.RecordDate, x.Value
FROM DataTable dt
CROSS APPLY(
SELECT TOP 1 Value
FROM Settings s
WHERE s.EffectiveDate <= dt.RecordDate
ORDER BY s.EffectiveDate DESC
) x