SQL SERVER 如何按当前时间排序

前端之家收集整理的这篇文章主要介绍了SQL SERVER 如何按当前时间排序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

  编程之家 jb51.cc

  问:数据库表有一列,表示预约完成时间,此时需要排序 就是 当预约完成的时间是今天的 排在最前,然后是当前时间以后的,然后才是过期的时间数据。不知道我描述清楚没有。。

  比如: 3个数据吧

  A 时间是 今天

  B 时间是明天

  C 时间是昨天

  取数据时候 排序为 a b c

  请问这样的sql怎么写?

  答:

以下为引用的内容
Create table Testtable(ID int identity(1,1),dt datetime)goinsert into Testtable(dt)select dateadd(dd,2,GETDATE())union allselect GETDATE()union allselect dateadd(dd,-2,GETDATE())union allselect GETDATE()declare @today varchar(20)set @today=CONVERT (VARCHAR(10),GETDATE(),121)declare @tommorrow varchar(20)set @tommorrow=CONVERT (VARCHAR(10),dateadd(dd,1,GETDATE()),121)--select @today--select @tommorrowselect * from Testtable where dt between cast(@today as datetime) and cast(@tommorrow as datetime) union allselect * from Testtable where dt>=cast(@tommorrow as datetime)union allselect * from Testtable where dt<=cast(@today as datetime)

猜你在找的MsSQL相关文章