首页 > 解决方案 > 根据另一列的最大值从表中选择列

问题描述

我有两个表,我想要基于最新完成时间的列输入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)

标签: sqldatejoinselectgreatest-n-per-group

解决方案


您可以在连接的子句中使用相关子查询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

您可以尝试解决方案并选择您更好理解或执行速度更快的解决方案。


推荐阅读