sql - 需要多条记录的最新行中的值
问题描述
我有以下内容:
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 行。
非常感谢任何帮助。
解决方案
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
推荐阅读
- python - 带有移动窗口的 Pandas 数据透视表
- java - 如何从地理围栏触发其他设备
- hibernate - 在同一张桌子上使用“多对一”和“一对一”
- android - 如何在数据类中初始化 GeoPoint 的默认值
- android - 无法通过 gmail 应用打开深层链接
- sql-server - 即使没有来自查找的行,Oledb 命令也会执行
- python - 如何查找特定文本并在其后打印接下来的 2 个单词
- javascript - 为什么我的 java 脚本计算器不工作
- docker - 如何在 AWS Amplify 中使用自定义构建映像?
- r - 为什么在函数内部时带有字符串向量的 group_by_at() 会失败?