您如何 select 最新日期的值?

How do you select the value for the latest date?

我试图简单地 select 具有最新时间戳的值,但由于某种原因,我的大脑有点冻结。

下面的代码是selecting所有记录:

SELECT S.idindicator, S.val ,[Time] = MAX(CAST(S.valTimestamp as date)), S.valTimestamp
FROM Status as S
WHERE S.INVALID = 0 
    AND S.id = 16888
GROUP by S.idindicator, S.val, S.valTimestamp 
ORDER BY S.valTimestamp DESC

我如何只 select 具有最新日期的 val,即 75.00?

注意:我使用相关子查询完成了它,但是,它变成了一个昂贵的查询。

您可能正在寻找像这样简单的东西:

SELECT TOP 1 S.idindicator, S.val , S.valTimestamp
FROM Status as S
WHERE S.INVALID = 0 AND S.id = 16888
GROUP by S.idindicator, S.val, S.valTimestamp 
ORDER BY S.valTimestamp DESC

编辑:正如评论中指出的那样,t-sql 中不存在限制,请改用前 1

如果您只需要一行,请使用 top (1)order by:

select top (1) *
from status s
where invalid = 0 and id = 16888
order by valTimestamp desc

如果你想在多个 id 上得到相同的结果,那么一个选项使用 window 函数:

select *
from (
    select s.*, row_number() over(partition by id order by valTimestamp desc) rn
    from status s
    where invalid = 0
) s
where rn = 1

如果您想允许平局,那么您可以在第一个查询中使用 top (1) with ties,在第二个查询中使用 rank() 而不是 row_number()