加入条件:按日期时间仅选择最后一条记录

时间:2017-09-13 10:18:05

标签: sql oracle oracle11g

我有这些表

特许权

Shipment_id,Title,Creation_datetime

1, A, 2017-09-13

并且每个特许权都有一个以上的SCAN

SCANS

Shipment_ID, Event_code, TSS_creation_date    
1, 200, 2017-09-10    
1, 400, 2017-09-11    
1, 600, 2017-09-12    
1, 800, 2017-09-15    
1, 900, 2017-09-16

在我的最终结果中我想要

结果(让步)

Shipment_ID,Title, Creation_datetime, LAST_SCAN_AT_CREATION_DATE

1, A, 2017-09-13, 600

我获得event_code=600,因为它是creation_date <= concession_creation_date

的最后一行

我已经尝试过这个查询,但它实在是效率低下而且速度太慢而无法获得结果。你知道如何使用Join吗?

WITH

ShipmentAndScans AS (
    SELECT
        conc.shipment_id,
        (
            SELECT 
                scan.event_code 
            FROM SCANS_TABLE scan 
            WHERE  
                    scan.shipment_id = conc.shipment_id
                AND scan.TSS_CREATION_DATE <= conc.CREATION_DATETIME
               AND ROWNUM <=1 

        ) AS LAST_SCAN_AT_CONCESSION_TIME           
    FROM CONCESSIONS conc        
)  
SELECT *
FROM ShipmentAndScans
WHERE LAST_SCAN_AT_CONCESSION_TIME IS NOT NULL

2 个答案:

答案 0 :(得分:0)

进行连接,使用row_number()

with CTE as
(
select c1.*, s2.*, 
       row_number() over(partition by c1.shipment_id order by TSS_creation_date desc) as rn
from Concessions
inner join SCANS s2
on s2.shipment_id = c1.shipment_id
)
select *
from CTE
where rn = 1

答案 1 :(得分:0)

我相信你想要以下内容:

select sc.*
from (select c.*, s.event_code, s.TSS_CREATION_DATE,
             row_number() over (partition by c.shipment_id order by s.tss_creation_date desc) as seqnum
      from concessions c join
           scan s
           on s.shipment_id = c.shipment_id and
              s.TSS_CREATION_DATE <= c.CREATION_DATETIME
     ) cs
where seqnum = 1;

在您的版本中,CTE基本上是LEFT JOIN(通过相关子查询)。但是,外部查询将该逻辑转回JOIN