sql - 根据另一列的最大值从表中选择列
问题描述
我有两个表,我想要基于最新完成时间的列输入first_table
和列输出second_table
第一表:
id input
--------------
1 America
2 China
3 Russia
2 China
3 Russia
second_table
id output finished_time
-------------------------------------------------
1 Washington 10/5/2019 10:05:13 PM +00:00
2 Shanghai 10/6/2019 10:05:13 PM +00:00
3 Kazan 10/7/2019 10:05:13 PM +00:00
2 Beijing 10/10/2019 10:05:13 PM +00:00
3 Moscow 10/11/2019 10:05:13 PM +00:00
结果表
id input output
-----------------------------
1 America Washington
2 China Beijing
3 Russia Moscow
我正在尝试使用此查询:
SELECT input, second_table.output
FROM first_table
INNER JOIN second_table ON first_table.id = second_table.id
AND Max(finished_time)
解决方案
您可以在连接的子句中使用相关子查询on
:
select
f.*,
s.output
from first_table f
inner join second_table s
on s.id = f.id
and s.finished_time = (
select max(s1.finished_time)
from second_table s1
where s1.id = s.id
)
对于此处的性能,您需要在second_table(id, finished_time)
.
这也可以用一个not exists
条件来表示:
select
f.*,
s.output
from first_table f
inner join second_table s
on s.id = f.id
and not exists (
select 1
from second_table s1
where s1.id = s.id
and s1.finished_time > s.finished_time
)
最后,另一种选择是使用窗口函数进行排名
select id, input, output
from (
select
f.*,
s.output,
rank() over(partition by s.id order by s.finished_time desc) rn
from first_table f
inner join second_table s on s.id = f.id
) x
where rn = 1
您可以尝试解决方案并选择您更好理解或执行速度更快的解决方案。
推荐阅读
- reactjs - 在 React 组件中通过 onMouseEnter 设置延迟状态
- javascript - 使用 find() 得到的对象进行三元运算
- c - 如果 fclose() 失败,文件描述符是否仍然打开?
- r - Knitr 上的自定义语言引擎
- c++ - 如何在 C++ 中打印动态数组我需要解释这个问题
- docker - 文件存在于 Singularity 容器中,但在执行时不会产生此类文件错误
- javascript - 合约部署后 Ganache 不更新账户余额
- c# - 侧边菜单的图像存储在哪里?
- php - 如何按日期顺序确定记录的编号
- uipath - 阻止用户与 UiPath 机器人交互