简体   繁体   English

根据匹配 ID 的时间戳获取上一行值

[英]Get previous row value based on a timestamp for matching IDs

I have a table about shipping that has information about the arrival (country and date) to a port.我有一张关于运输的表格,其中包含有关到达港口的信息(国家和日期)。 Now I need to extract the country where it departed from using the previous row entries.现在我需要使用前面的行条目提取它离开的国家/地区。 The table looks like this桌子看起来像这样

ID ID CountryArrival国家到达 DateArrival到达日期
1 1个 BE 1-1-2022 1-1-2022
2 2个 US我们 1-1-2022 1-1-2022
1 1个 NL荷兰语 2-1-2022 2-1-2022
2 2个 IT 4-1-2022 4-1-2022
1 1个 PT PT 5-1-2022 5-1-2022

I want to obtain the departure for each ID based on the previous ArrivalDate so it would look like this我想根据之前的 ArrivalDate 获取每个 ID 的出发时间,所以它看起来像这样

ID ID CountryArrival国家到达 DateArrival到达日期 DeparturePort出发港
1 1个 BE 1-1-2022 1-1-2022 NULL NULL
2 2个 US我们 1-1-2022 1-1-2022 NULL NULL
1 1个 NL荷兰语 2-1-2022 2-1-2022 BE
2 2个 IT 4-1-2022 4-1-2022 US我们
1 1个 PT PT 5-1-2022 5-1-2022 NL荷兰语

I can obtain the previous Country based only on DateArrival with:我可以仅基于 DateArrival 获得以前的国家:

select 
 pc.*,
    lag(pc.CountryArrival) over (order by DateArrival) as DeparturePort
from shipping pc
where pc.DateArrival is not null;

Any idea how to get the previous arrival for matching IDs?知道如何获得匹配 ID 的先前到达时间吗?

You need to PARTITION BY the ID column.您需要按ID列进行PARTITION BY

 lag(pc.CountryArrival) over (PARTITION BY ID order by DateArrival) as DeparturePort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM