所以我有一个下面的表格:
CreatedAt ID NewStatus OldStatus
2023-03-08 13:34:57.0000000 1645 Draft NULL
2023-03-22 19:58:51.0000000 1645 Active Draft
2023-04-29 05:59:02.0000000 1645 Closed Active
2023-05-08 14:50:29.0000000 1645 Awarded Closed
2023-05-08 14:53:34.0000000 1645 ConfirmationStarted Awarded
2023-05-08 17:53:55.0000000 1645 ConfirmationDone ConfirmationStarted
我想获取这个ID在"ObservationStarted"之前得到"Closed"的日期,所以在这种情况下,我会得到以下结果
ID xdate
1645 2023-04-29 05:59:02.0000000
我写了一个T—SQL查询:
WITH StatusChanges AS (
SELECT
ID,
newstatus,
oldstatus,
CreatedAt,
LEAD(newstatus) OVER (PARTITION BY IDORDER BY CreatedAt) AS next_status
FROM
tableA
)
SELECT
ID,
MAX(CreatedAt) AS xdate
FROM
StatusChanges
WHERE
next_status = 'Confirmation Started' and OldStatus = 'Closed'
GROUP BY
ID;
此查询适用于大多数情况,例如此ID
CreatedAt ID NewStatus OldStatus
2022-05-25 23:17:44.0000000 147 Active Closed
2022-05-28 05:59:02.0000000 147 Closed Active
2022-05-30 20:48:53.0000000 147 Active Closed
2022-06-18 05:59:01.0000000 147 Closed Active
2022-06-21 20:09:48.0000000 147 Active Closed
2022-06-25 05:59:01.0000000 147 Closed Active
2022-07-13 00:02:47.0000000 147 ConfirmationStarted Closed
2022-07-15 15:33:30.0000000 147 ConfirmationDone ConfirmationStarted
我想要的日期:2022-06-25 05:59:01.0000000
1645 ID怎么办?