[英]Pick Max Date from Table
I have a table variable defined thus 我因此定义了一个表变量
DECLARE @DatesTable TABLE
(
Id uniqueidentifier,
FooId uniqueidentifier,
Date date,
Value decimal (26, 10)
)
Id is always unique but FooId is duplicated throughout the table. Id始终是唯一的,但FooId在整个表中都是重复的。 What I would like to do is to select * from this table for each unique FooId having the max(date).
我想为每个具有max(date)的唯一FooId从此表中选择*。 So, if there are 20 rows with 4 unique FooIds then I'd like 4 rows, picking the row for each FooId where the date is the largest.
因此,如果有20行具有4个唯一的FooId,则我希望有4行,为日期最大的每个FooId选择一行。
I've tried using group by but I kept getting errors about various fields not being in the select clause etc. 我试过使用group by,但是我不断收到关于各个字段不在select子句等中的错误。
Use a common table expression with row_number()
: 使用带有
row_number()
的公用表表达式:
;WITH cte AS
(
SELECT Id, FooId, Date, Value,
ROW_NUMBER() OVER(PARTITION BY FooId ORDER BY Date DESC) As rn
FROM @DatesTable
)
SELECT Id, FooId, Date, Value
FROM cte
WHERE rn = 1
Often the most efficient method is a correlated subquery: 通常,最有效的方法是相关子查询:
select dt.*
from @DatesTable dt
where dt.date = (select max(dt2.date) from @DatesTable dt2 where dt2.fooid = dt.fooid);
However, for this to be efficient, you need an index on (fooid, date)
. 但是,为了使其高效,您需要在
(fooid, date)
上建立索引。 In more recent versions of SQL Server, you can have indexes on table variables. 在SQL Server的最新版本中,可以在表变量上具有索引。 In earlier versions, you can do this using a primary key.
在早期版本中,可以使用主键来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.