根据条件识别其他行之后的行?

Identify rows subsequent to other rows based on criteria?

我是 DB2 的新手,SQL。存在 table 的客户及其访问。当 Sale = 'Y'.

时,我需要编写一个查询来查找同一客户随后和 24 小时内的访问

基于此示例数据:

CustomerId VisitID Sale DateTime
1 1 Y 2021-04-23 20:16:00.000000
2 2 N 2021-04-24 20:16:00.000000
1 3 N 2021-04-23 21:16:00.000000
2 4 Y 2021-04-25 20:16:00.000000
3 5 Y 2021-04-23 20:16:00.000000
2 6 N 2021-04-25 24:16:00.000000
3 7 N 2021-5-23 20:16:00.000000

查询结果应该return:

VisitID
3
6

我该怎么做?

试试这个。您可以取消对 运行 此语句原样的注释块的注释。

/*
WITH MYTAB (CustomerId, VisitID, Sale, DateTime) AS
(
VALUES
  (1, 1, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (1, 3, 'N', '2021-04-23 21:16:00'::TIMESTAMP)
, (2, 2, 'N', '2021-04-24 20:16:00'::TIMESTAMP)
, (2, 4, 'Y', '2021-04-25 20:16:00'::TIMESTAMP)
, (2, 6, 'N', '2021-04-25 23:16:00'::TIMESTAMP)
, (3, 5, 'Y', '2021-04-23 20:16:00'::TIMESTAMP)
, (3, 7, 'N', '2021-05-23 20:16:00'::TIMESTAMP)
)
*/
SELECT VisitID
FROM MYTAB A
WHERE EXISTS
(
SELECT 1
FROM MYTAB B
WHERE B.CustomerID = A.CustomerID
AND B.Sale = 'Y'
AND B.VisitID <> A.VisitID
AND A.DateTime BETWEEN B.DateTime AND B.DateTime + 24 HOUR
)