按日期时间字段选择最新记录

时间:2009-10-26 20:40:01

标签: sql sql-server tsql

如何按SQL Server的日期时间选择最新记录?

这是伪代码......

SELECT Records 
  FROM MyTable 
 WHERE current time >= (CurrentTime - 2 minutes)

假设当前时间是10:25:39 pm

26/10/2009 10:25:39 pm
26/10/2009 10:25:00 pm
26/10/2009 10:24:53 pm
26/10/2009 10:24:19 pm
26/10/2009 10:23:58 pm
26/10/2009 10:14:56 pm
26/10/2009 10:12:56 pm

SQL查询应返回这些记录......

26/10/2009 10:25:39 pm
26/10/2009 10:25:00 pm
26/10/2009 10:24:53 pm
26/10/2009 10:24:19 pm

2 个答案:

答案 0 :(得分:7)

真实代码:

SELECT * FROM MyTable WHERE currentTime >= DATEADD(n, -2,  GETDATE())
ORDER BY currentTime DESC

答案 1 :(得分:3)

使用:

WHERE t.currenttime BETWEEN DATEADD(mi, -2, GETDATE()) AND GETDATE()
ORDER BY t.currenttime DESC

参考文献: