[英]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 ![]() |
CountryArrival![]() |
DateArrival![]() |
---|---|---|
1 ![]() |
BE![]() |
1-1-2022 ![]() |
2 ![]() |
US![]() |
1-1-2022 ![]() |
1 ![]() |
NL![]() |
2-1-2022 ![]() |
2 ![]() |
IT![]() |
4-1-2022 ![]() |
1 ![]() |
PT ![]() |
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 ![]() |
CountryArrival![]() |
DateArrival![]() |
DeparturePort![]() |
---|---|---|---|
1 ![]() |
BE![]() |
1-1-2022 ![]() |
NULL ![]() |
2 ![]() |
US![]() |
1-1-2022 ![]() |
NULL ![]() |
1 ![]() |
NL![]() |
2-1-2022 ![]() |
BE![]() |
2 ![]() |
IT![]() |
4-1-2022 ![]() |
US![]() |
1 ![]() |
PT ![]() |
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.