DEFINE @param DATE = '07/01/2017';
SELECT TOP 1 leasecode
FROM t WHERE convert(date,dbo.ToDateTime(ExpDate)) <= convert(date,@param)
ORDER BY t.date DESC;
通過最近你的意思是對用戶提供的日期或之前的日期的第一條記錄,或者最近在絕對差的日期?另外,由於您使用DAY,您想如何在同一天處理租賃代碼? Sry無法測試日期條件,而不是現在在機器之前。
/* one row only - with arbitrary resolution of ties absolute dstance */
WITH d AS (
SELECT *,ROW_NUMBER() OVER (ORDER BY
ABS(datediff(day, CONVERT(date, dbo.ToDateTime(ExpDate)) , convert(date, @param)) AS dst FROM t
)
SELECT * FROM d WHERE dst = 1;
/* all rows that with and ExpDate the same number of absolute days from your parameter */
WITH d AS (
SELECT *,DENSE_RANK() OVER (ORDER BY
ABS(datediff(day, CONVERT(date, dbo.ToDateTime(ExpDate)) , convert(@param , date))) AS dst FROM t
)
SELECT * FROM d WHERE dst = 1;
更接近'2017年7月1日'..這是否意味着日期也可以在'7/1/2017'之前? –