从SQL Server中具有过去和未来日期的记录列表中获取当前生效日期
我在SQL Server数据库表中有一个列EffectiveOn的记录列表。我想获取当前日期对应的当前适用生效日期。考虑下表从SQL Server中具有过去和未来日期的记录列表中获取当前生效日期,sql,sql-server,Sql,Sql Server,我在SQL Server数据库表中有一个列EffectiveOn的记录列表。我想获取当前日期对应的当前适用生效日期。考虑下表 Id Data EffectiveOn _____________________________________ 1 abc 2020-04-28 2 xyz 2020-08-05 3 dhd 2020-10-30 4 e
Id Data EffectiveOn
_____________________________________
1 abc 2020-04-28
2 xyz 2020-08-05
3 dhd 2020-10-30
4 ert 2020-12-28
5 lkj 2021-03-19
在上表中,我必须获取记录Id:3,因为当前日期,即今天是2020-11-19
预期结果集
Id Data EffectiveOn
_____________________________________
3 dhd 2020-10-30
我尝试了以下解决方案,但我做不到
请帮助我如何获得预期结果集。您可以执行以下操作:
select top (1) *
from mytable t
where effectiveon <= convert(date, getdate())
order by effectiveon desc
这将选择今天或今天之前的最长日期(如果可用)。您可以尝试使用行数功能
select id, data, effectiveon
(
select ROW_NUMBER()over(order by effectiveon desc )sno,* from #table
where effectiveon < cast(getdate() as date)
)a where sno=1