首页 > 解决方案 > 需要多条记录的最新行中的值

问题描述

我有以下内容:

UserID    SomeValue     DateUpdated
------------------------------------
1         263           2019-09-07
2         abc           2019-09-10
1         123           2019-09-10
2         234           2019-09-11
1         573           2019-09-20

我需要一个查询,它将返回不同的 UserID、最近的 DateUpdated 值以及最近记录的相应 SomeValue。

我在同一个表的子查询上尝试了外连接。没有产生预期的结果。

SELECT B.UserID, B.SomeValue, B.DateUpdated 
FROM thetable B
LEFT OUTER JOIN 
(SELECT UserID, MAX(DateUpdated) AS DateUpdated 
 FROM thetable GROUP BY UserID) x
ON x.UserID = B.UserID AND x.DateUpdated = B.DateUpdated

但它的回报比预期的要多得多。

从上面的数据示例中,我希望得到:

UserID    SomeValue     DateUpdated
------------------------------------
2         234           2019-09-11
1         573           2019-09-20

在我的生产表中,我有 3,670,108 条记录。外连接返回 3,669,774,但表中只有 1,182,525 个不同的 UserID。所以我希望结果是 1,182,525 行。

非常感谢任何帮助。

标签: sqlsql-server

解决方案


row_number()

select userid, somevalue, dateupdated
from (
  select *, row_number() over (partition by userid order by dateupdated desc) rn
  from thetable
) t
where rn = 1

或者不存在:

select t.* from thetable t
where not exists (
  select 1 from thetable
  where userid = t.userid and dateupdated > t.dateupdated 
)

请参阅演示
结果:

> userid | somevalue | dateupdated        
> -----: | :-------- | :----------
>      1 | 573       | 2019-09-20 
>      2 | 234       | 2019-09-11 

推荐阅读