2017-03-06 54 views
0

我加入了2個表客戶&配置文件。兩個表都由特定的列cust_id連接。在個人資料表中,我有超過1個條目。我想在連接兩個表時通過start_ts(column)選擇最近的條目。因此,我希望在結果集中包含來自客戶的1行 - 來自配置文件的最近行。有沒有辦法做到這一點OR​​ACLE SQL?獲取最近的記錄作爲連接的一部分

回答

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

@PunterVicky - 如果你和Oracle一起工作,你也可以對其他使用多個連接的人的Gordon解決方案進行測試。戈登的解決方案可能證明效率更高(更快)。爲Oracle支付大筆資金的原因正是他們擁有的額外的東西(其他SQL數據庫產品可能沒有),儘管分析功能非常標準。引入分析函數的目的是減少查詢中耗時的連接數量。 – mathguy

+0

謝謝@Gordon&mathguy。我也會試試這個! –

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 
+0

感謝@juergen。我會試試這個。 「適用於所有數據庫引擎」的 –

+0

可能是一件好事,但它也可能是一件壞事。如果用戶在Oracle產品上花費大筆資金,他們可能會充分利用所有數據庫引擎中不一定提供的Oracle功能。在這種情況下,分析函數可能會比重複連接提供更快的解決方案。 – mathguy

+0

我同意....... –

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 
    ) 
+0

謝謝@maraca! –