获取最接近的上一个日期T-SQL

时间:2022-07-27 20:12:18

I need to get select the closest previous date to a date parameter. Currently I am selecting the closest either side of the date using this code:

我需要选择最接近日期参数的前一个日期。目前我使用此代码选择最接近日期的任何一方:

SELECT TOP 1 equities, fund, e_date
        FROM tbl_assetmix
        WHERE fund = @fund_code
        ORDER BY ABS(DateDiff(dd, e_date, @statementdate)) asc

I know it is really simple but can someone suggest how I would be able to select the closest date prior to the @statementdate parameter?

我知道这很简单,但有人可以建议我如何能够在@statementdate参数之前选择最接近的日期吗?

Thanks, Tristan

1 个解决方案

#1


3  

Select just lines where date is prior to @statementdate:

选择日期在@statementdate之前的行:

SELECT TOP 1 equities, fund, e_date
FROM tbl_assetmix
WHERE fund = @fund_code
AND e_date < @statementdate
ORDER BY ABS(DateDiff(dd, e_date, @statementdate)) asc

or replace the

或者更换

AND e_date < @statementdate

with

AND e_date <= @statementdate

if the same day is allowed.

如果允许同一天。

#1


3  

Select just lines where date is prior to @statementdate:

选择日期在@statementdate之前的行:

SELECT TOP 1 equities, fund, e_date
FROM tbl_assetmix
WHERE fund = @fund_code
AND e_date < @statementdate
ORDER BY ABS(DateDiff(dd, e_date, @statementdate)) asc

or replace the

或者更换

AND e_date < @statementdate

with

AND e_date <= @statementdate

if the same day is allowed.

如果允许同一天。