SQL中如何根据列条件获取下一个时间戳?

问题描述 投票:0回答:1

我有一张看起来像这样的桌子

事件_d event_lcl_ts 位置_id 事件代码 容器 ID
4/6/24 2024-04-06T10:19:32.133+00:00 1 上架 asdjhdf-323
4/6/24 2024-04-06T21:52:35.019+00:00 1 接收 asdjhdf-323
4/7/24 2024-04-07T00:13:17.496+00:00 1 上架 asdjhdf-323
4/7/24 2024-04-07T12:35:54.766+00:00 1 接收 asdjhdf-323
4/7/24 2024-04-07T16:27:13.245+00:00 1 上架 asdjhdf-323
4/8/24 2024-04-08T22:56:19.038+00:00 1 接收 asdjhdf-323
4/9/24 2024-04-09T00:19:47.575+00:00 1 上架 asdjhdf-323
4/10/24 2024-04-10T20:44:12.190+00:00 1 接收 asdjhdf-323
4/11/24 2024-04-11T01:14:45.466+00:00 1 上架 asdjhdf-323
4/11/24 2024-04-11T10:14:12.709+00:00 1 接收 asdjhdf-323
4/11/24 2024-04-11T12:57:11.640+00:00 1 上架 asdjhdf-323

我正在尝试创建一行,其中显示收到容器然后存放的时间戳,该时间戳基于

event_code
。此数据的一个警告是,在某些情况下,根据提取数据的时间范围,将填充
PUTAWAY
事件,而没有其先前的
RECEIVE
事件。也可能存在在最近的
PUTAWAY
事件中尚未发生
RECEIVE
事件的情况。

在这种情况下,理想的输出将是这样的:

容器 ID 接收时间戳 放置_时间戳 位置_id
asdjhdf-323 2024-04-06T21:52:35.019+00:00 2024-04-07T00:13:17.496+00:00 1
asdjhdf-323 2024-04-07T12:35:54.766+00:00 2024-04-07T16:27:13.245+00:00 1
asdjhdf-323 2024-04-08T22:56:19.038+00:00 2024-04-09T00:19:47.575+00:00 1
asdjhdf-323 2024-04-10T20:44:12.190+00:00 2024-04-11T01:14:45.466+00:00 1
asdjhdf-323 2024-04-11T10:14:12.709+00:00 2024-04-11T12:57:11.640+00:00 1

如何在忽略或过滤

PUTAWAY
之前可能存在
RECEIVE
事件的情况下执行此操作?在本例中 - 第一行。谢谢!

sql hive
1个回答
1
投票

如果您确定行始终交错,您可以使用

LAG
LEAD

SELECT
  t.container_id,
  t.event_lcl_ts AS receive_timestamp,
  t.putaway_timestamp,
  t.location_id
FROM (
    SELECT t.*,
      LEAD(CASE WHEN t.event_code = 'PUTAWAY' THEN t.event_lcl_ts END)
        OVER (PARTITION BY t.location_id, t.container_id ORDER BY t.event_lcl_ts) AS putaway_timestamp
    FROM YourTable AS t
) AS t
WHERE t.event_code = 'RECEIVE';
© www.soinside.com 2019 - 2024. All rights reserved.