SQL语句根据日期时间获取最新记录

时间:2018-12-27 23:38:26

标签: sql-server

我需要查询帮助以基于数据库中的DateTime列来获取最新记录。其格式为YYYY-MM-DD HH:MINS:SEC:Milliseconds

每当在数据库中创建新记录时,只有那些记录必须被提取并显示在第三方应用程序中。

在下面的查询中提取应用程序的所有记录,我们可以将其放在子查询中并仅提取最近的记录或其他最佳方式吗?

SELECT 
    User.ID, User_State.Name, User_State.Code, User_State.TestState,
    Details.FirstName, Details.LastName, Details.LoginName,
    User_State.DateTime,call.QueueCalls, call.CallsAband 
FROM 
    User
INNER JOIN 
    User_State ON User.ID = User_State.ID
INNER JOIN 
    Details ON User.ID = Details.ID
INNER JOIN  
    Call ON User_State.Key = Call.Key
WHERE 
    User_State.DateTime >= CONVERT(DateTIme, DATEDIFF(DAY, 0, GETDATE())) 
ORDER BY 
    DateTime DESC

1 个答案:

答案 0 :(得分:0)

如果该查询返回所有行,则可以通过在select语句中使用TOP n子句来限制行数,也可以在CTE中使用row_number()。取决于您要返回多少行。我不理解您的where子句。

ROW_number如下所示的示例-

 SELECT row,User.ID, User_State.Name, User_State.Code, User_State.TestState
 , Details.FirstName, Details.LastName, Details.LoginName
 , User_State.DateTime,call.QueueCalls, call.CallsAband 
 FROM(
  SELECT ROW_NUMBER() OVER (ORDER BY User_State.DateTime) AS row,
  User.ID, User_State.Name, User_State.Code, User_State.TestState
 , Details.FirstName, Details.LastName, Details.LoginName
 , User_State.DateTime,call.QueueCalls, call.CallsAband 
 FROM User
  INNER JOIN User_State ON User.ID = User_State.ID
  INNER JOIN Details ON User.ID = Details.ID
  INNER JOIN Call ON User_State.Key = Call.Key
  WHERE User_State.DateTime >= GETDATE()
  ) AS CTE
  where CTE.row<10
 ORDER BY CTE.DateTime DESC