sql选择最新值

时间:2011-03-30 09:45:30

标签: sql

我有以下SQL语句

SELECT [Motor]
      ,[Time]
  FROM [logger].[dbo].[motor]
  WHERE day([Time]) = day(getdate())
  ORDER BY [TIME]

这是一个非常基本的表格,它给出了给定时间电机的状态。

我想要的只是一个select语句,如果可能的话会给我最新的结果。我可以得到它所以它给出了今天的所有结果但是如果我能得到它以便它只显示最新的结果那将是伟大的。

3 个答案:

答案 0 :(得分:5)

要“仅显示最新结果”,您只需使用TOP

SELECT TOP (1) [Motor] ,[Time] 
FROM [logger].[dbo].[motor] 
ORDER BY [TIME] desc

或者(如果你想要每个电机的TOP 1

WITH cte As
(
SELECT  [Motor] ,
        [Time], 
        ROW_NUMBER() OVER (PARTITION BY [Motor] ORDER BY [TIME] DESC) RN
FROM [logger].[dbo].[motor] 
)
SELECT [Motor] ,[Time]
FROM cte
WHERE RN=1

答案 1 :(得分:2)

SELECT TOP(1) [Motor] ,[Time] 
FROM [logger].[dbo].[motor] 
WHERE day([Time]) = day(getdate()) 
ORDER BY [TIME] DESC

答案 2 :(得分:2)

“最新”是TOP 1ORDER BY [x] DESC - 但是,我不认为查询是正确的; day返回当月的日期,而不是日期时间的仅日期部分:

DECLARE @today datetime = CAST(FLOOR(CAST(getdate() as float)) as datetime)
DECLARE @tomorrow datetime = @today + 1

SELECT TOP 1 [Motor], [Time]
FROM [logger].[dbo].[motor]
WHERE [Time] >= @today AND [Time] < @tomorrow
ORDER BY [Time] DESC

注意我选择保留你的“今天”语义;如果你有未来的数据,这可能很重要。