Leetcode Problem 1972. First and Last Call On the Same Day

1972. First and Last Call On the Same Day

Leetcode Solutions

UNION + RANK() + HAVING()

  1. Use UNION to combine two SELECT queries, one where the user is the caller and another where the user is the recipient, to create a unified view of calls with user_id and recipient_id.
  2. Create a CTE (CTE1) from the unified view, where we partition by user_id and call date, and use the DENSE_RANK() window function to assign ranks in ascending and descending order of call_time.
  3. Select distinct user_id from CTE1 where the rank is 1 (first or last call of the day).
  4. Group the results by user_id and call date.
  5. Use the HAVING clause to filter groups where the count of distinct recipient_id is 1, indicating the first and last calls were with the same person.

erDiagram
    Calls {
        int caller_id
        int recipient_id
        datetime call_time
    }

MySQL using CTE + window function - first_value

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...