获取最新记录作为联接的一部分

时间:2017-03-06 21:21:24

标签: sql oracle

我正在加入2个表客户&轮廓。这两个表都由特定列cust_id连接。在个人资料表中,我有超过1个条目。我想在连接两个表时通过start_ts(列)选择最近的条目。因此,我想要一行 - 来自客户的行和结果集中来自配置文件的最新行。有没有办法做这个ORACLE SQL?

3 个答案:

答案 0 :(得分:3)

我会使用窗口函数:

select . . .
from customer c join
     (select p.*,
             row_number() over (partition by cust_id order by start_ts desc) as seqnum
      from profile
     ) p
     on c.cust_id = p.cust_id and p.seqnum = 1;

如果您希望获得不具备个人资料的客户,则可以使用left join

答案 1 :(得分:2)

一种方法(适用于所有数据库引擎)是加入要从中选择数据的表,然后根据profile的特定最大记录加入以过滤数据

select c.*, p.*
from customer c
join profile p on c.cust_id = p.cust_id
join
(
    select cust_id, max(start_ts) as maxts
    from profile
    group by cust_id
) p2 on p.cust_id = p2.cust_id and p.start_ts = p2.maxts

答案 2 :(得分:1)

这是另一种方式(如果没有更新的条目,那么它是最新的):

select
   c.*,
   p.*
from
   customer c inner join
   profile p on p.cust_id = c.cust_id and not exists(
      select *
      from profile
      where cust_id = c.cust_id and start_ts > p.start_ts
   )
相关问题