SQL 查找第一个和最后一个来电者 phone 在给定日期给同一个人打电话

SQL to find callers first and last phone call to the same person on a given day

这是我正在使用的table。 Table 名字是 phone_log

caller_id  recipient_id        call_start_time
1          2                  2012-04-19 09:00:00
2          3                  2012-04-19 17:00:00
1          2                  2012-04-19 23:00:00
...       ...                             ...

我需要找出谁在给定的一天给同一个人打了第一个和最后一个电话。我不知道从哪里开始。感谢对此的任何建议。

我想要的输出如下所示:

caller_id    recipient_id        call_start_time
   1             2                 2012-04-19   

一种方法使用 first_value():

select distinct caller_id, first_recipient_id
from (select pl.*,
             first_value(recipient_id) over (partition by caller_id, date(call_start_time) order by call_start_time) as first_recipient_id,
             first_value(recipient_id) over (partition by caller_id, date(call_start_time) order by call_start_time desc) as last_recipient_id
      from phone_log pl
     ) pl
where first_recipient_id = last_recipient_id;

这使用 date() 等函数从 date/time 中提取日期。 Date/time 函数因数据库而异。