每天进步一点点之SQL 获取表中某个时间字段离当前时间最近的几条

实际中用到的SQL:

 select * from (select top 3 Id,
 case when startSignup>GETDATE() then '敬请期待' when (startSignup<GETDATE() and  endsignUp>=getdate()) then '正在报名'
 when (StartDate<GETDATE() and EndDate>=GETDATE())or (StartDate<GETDATE() and EndDate is null) then '正在进行' when EndDate<GETDATE() then '已经结束' else '' end [status], Name,VerifyCode,StartDate, EndDate, TrainType, AddTime, CheckStatus, [Disable],StartSignup, EndSignup, SignupLimit,[Price] from Train A where  A.CheckStatus=1
 and A.[Disable]=0 and A.TrainType=1 and Name  not like '%测试%' order by ABS(convert(float,A.StartDate-GETDATE())))B order by startdate desc,B.Enddate desc

关键字:order by ABS(convert(float,A.StartDate-GETDATE()))

其中还需要注意:

时间是可以直接比较的,但是会很精确。如果只需要比较年月日的话,convert(varchar(10),getdate(),120)) 转化一下 即可,是2014-07-04 格式的。

原文地址:https://www.cnblogs.com/sunShineJing/p/3807883.html