简体   繁体   中英

Get closest previous date T-SQL

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?

Thanks, Tristan

Select just lines where date is prior to @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM