使用 SQLite:假设我有这样的
Calls
表:
index_call start_datetime nextcall_datetime
--------------------------------------------------
1 2024-01-01 08:00AM 2024-01-01 08:24AM
2 2024-01-01 08:24AM 2024-01-01 08:35AM
3 2024-01-01 08:35AM 2024-01-01 08:45AM
还有一个
Event
表如下:
id_event id_datetime
------------------------------
1 2024-01-01 08:04AM
2 2024-01-01 08:12AM
3 2024-01-01 08:25AM
4 2024-01-01 08:30AM
然后我需要获取两次调用之间发生的事件,但如果有多个事件,则只取最后一次发生的事件。
我尝试了以下操作,但这会从两个表中生成笛卡尔积。
SELECT
calls.index_call,
calls.start_datetime,
calls.nextcall_datetime,
event.id_datetime
FROM
calls calls
LEFT JOIN
event event
WHERE
events.CreatedDate BETWEEN calls.start_datetime AND calls.nextcall_datetime
预期结果:
index_call start_datetime nextcall_datetime id_datetime
-----------------------------------------------------------------------
1 2024-01-01 08:00AM 2024-01-01 08:24AM 2024-01-01 08:12AM
2 2024-01-01 08:24AM 2024-01-01 08:35AM 2024-01-01 08:30AM
3 2024-01-01 08:35AM 2024-01-01 08:45AM
尝试如下:
SELECT *
FROM ( Select c.INDEX_CALL, START_DATETIME, NEXTCALL_DATETIME,
e.ID_EVENT, ID_DATETIME,
ROW_NUMBER() OVER(Partition By c.INDEX_CALL Order By e.ID_DATETIME Desc) "RN_ORDER"
From calls c
Left Join event e ON(e.ID_DATETIME >= c.START_DATETIME And e.ID_DATETIME < c.NEXTCALL_DATETIME)
)
WHERE RN_ORDER = 1