需要检索表的最后插入/更新的记录,包括一些排除项

时间:2019-01-25 18:01:21

标签: sql db2

我正在尝试检索在表SHIPMENT_EVENT中插入/更新的最后一条记录。有一些不需要的事件/代码,例如全部以“ 9”开头的事件/代码。问题是这些事件始终是最后发送的事件,但对我来说最不重要,因此我需要显示最后一个事件,但是如果该事件是9X事件,则不应显示它,而应继续查找直到到达有效代码以显示之前,最后一个不是9X的事件。

以下是我认为对我的案情有所帮助的代码。此左联接应检查事件表并检索上一个事件。但是,经过深入测试,当最后一个事件是9X时,它显示的是NULL。

我尝试将NOT LIKE子句移动到第一个块的外面,但结果相同。我注意到直接删除不喜欢的图片是错误的,最终我得到了9X事件的所有结果。

left join 

(    select ship_id, ship_to_loc_cd856, ship_evnt_cd, updt_job_tms, 
carr_tracking_num, event_srv_lvl
         FROM
         (   select  ship_id, ship_to_loc_cd856, ship_evnt_cd, 
updt_job_tms, carr_tracking_num, event_srv_lvl
            ,        row_number() over(partition by ship_id order by 
updt_job_tms desc) as RN
          FROM     shipment_event
         ) s
         WHERE RN = 1  and ship_evnt_cd not like ('9%')
        )  AS lscus
ON        scus.ship_id=lscus.ship_id and 
scus.ship_to_loc_code=lscus.ship_to_loc_cd856

我需要检查最近事件并进行检索的逻辑,但是如果它是9X,则继续寻找下一个非9x事件。

谢谢

2 个答案:

答案 0 :(得分:1)

您的问题是您要在获取最新行后的 中过滤掉不需要的事件:

WHERE RN = 1  and ship_evnt_cd not like ('9%')

您需要先进行过滤,然后从剩下的列表中获取最新的行:

LEFT JOIN (SELECT ship_id, ship_to_loc_cd856, ship_evnt_cd, 
                  updt_job_tms, carr_tracking_num, event_srv_lvl, 
                  ROW_NUMBER() OVER(PARTITION BY ship_id ORDER BY updt_job_tms DESC) AS rn
           FROM Shipment_Event
           -- This _might_ perform better than the NOT LIKE condition, you'll need to test
           WHERE LEFT(ship_evnt_cd, 1) <> '9') lscus
       ON lscus.ship_id = scus.ship_id 
          AND lscus.ship_to_loc_cd856 = scus.ship_to_loc_code 
          AND lscus.rn = 1

答案 1 :(得分:0)

如果您有一些ship_id只具有9%个事件,那么您将需要例如

select  ship_id, ship_to_loc_cd856, ship_evnt_cd
,     updt_job_tms, carr_tracking_num, event_srv_lvl
,     row_number() over(partition by ship_id order by updt_job_tms desc) as RN
FROM    shipment_event e
WHERE   ship_evnt_cd not like '9%'
    OR  NOT EXISTS (SELECT 1 from shipment_event s 
                    WHERE s.ship_id = e.ship_id 
                     AND ship_evnt_cd not like '9%')

作为您的子选择