返回介绍

solution / 1900-1999 / 1972.First and Last Call On the Same Day / README_EN

发布于 2024-06-17 01:03:12 字数 3080 浏览 0 评论 0 收藏 0

1972. First and Last Call On the Same Day

中文文档

Description

Table: Calls

+--------------+----------+
| Column Name  | Type   |
+--------------+----------+
| caller_id  | int    |
| recipient_id | int    |
| call_time  | datetime |
+--------------+----------+
(caller_id, recipient_id, call_time) is the primary key (combination of columns with unique values) for this table.
Each row contains information about the time of a phone call between caller_id and recipient_id.

 

Write a solution to report the IDs of the users whose first and last calls on any day were with the same person. Calls are counted regardless of being the caller or the recipient.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Calls table:
+-----------+--------------+---------------------+
| caller_id | recipient_id | call_time       |
+-----------+--------------+---------------------+
| 8     | 4      | 2021-08-24 17:46:07 |
| 4     | 8      | 2021-08-24 19:57:13 |
| 5     | 1      | 2021-08-11 05:28:44 |
| 8     | 3      | 2021-08-17 04:04:15 |
| 11    | 3      | 2021-08-17 13:07:00 |
| 8     | 11       | 2021-08-17 22:22:22 |
+-----------+--------------+---------------------+
Output: 
+---------+
| user_id |
+---------+
| 1     |
| 4     |
| 5     |
| 8     |
+---------+
Explanation: 
On 2021-08-24, the first and last call of this day for user 8 was with user 4. User 8 should be included in the answer.
Similarly, user 4 on 2021-08-24 had their first and last call with user 8. User 4 should be included in the answer.
On 2021-08-11, user 1 and 5 had a call. This call was the only call for both of them on this day. Since this call is the first and last call of the day for both of them, they should both be included in the answer.

Solutions

Solution 1

# Write your MySQL query statement below
with s as (
  select
    *
  from
    Calls
  union
  all
  select
    recipient_id,
    caller_id,
    call_time
  from
    Calls
),
t as (
  select
    caller_id user_id,
    FIRST_VALUE(recipient_id) over(
      partition by DATE_FORMAT(call_time, '%Y-%m-%d'),
      caller_id
      order by
        call_time asc
    ) first,
    FIRST_VALUE(recipient_id) over(
      partition by DATE_FORMAT(call_time, '%Y-%m-%d'),
      caller_id
      order by
        call_time desc
    ) last
  from
    s
)
select
  distinct user_id
from
  t
where
  first = last

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文