LeetCode Problem 1699.
Table: Calls
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| from_id | int |
| to_id | int |
| duration | int |
+-------------+---------+
This table does not have a primary key, it may contain duplicates.
This table contains the duration of a phone call between from_id and to_id.
from_id != to_id
Write an SQL query to report the number of calls and the total call duration between each pair of distinct persons (person1, person2) where person1 < person2.
Return the result table in any order.
The query result format is in the following example:
Calls table:
+---------+-------+----------+
| from_id | to_id | duration |
+---------+-------+----------+
| 1 | 2 | 59 |
| 2 | 1 | 11 |
| 1 | 3 | 20 |
| 3 | 4 | 100 |
| 3 | 4 | 200 |
| 3 | 4 | 200 |
| 4 | 3 | 499 |
+---------+-------+----------+
Result table:
+---------+---------+------------+----------------+
| person1 | person2 | call_count | total_duration |
+---------+---------+------------+----------------+
| 1 | 2 | 2 | 70 |
| 1 | 3 | 1 | 20 |
| 3 | 4 | 4 | 999 |
+---------+---------+------------+----------------+
Users 1 and 2 had 2 calls and the total duration is 70 (59 + 11).
Users 1 and 3 had 1 call and the total duration is 20.
Users 3 and 4 had 4 calls and the total duration is 999 (100 + 200 + 200 + 499).
A call from 1 to 2 and a call from 2 to 1 belong to the same pair. To group them together, write every call with the smaller id first:
person1 = LEAST(from_id, to_id)person2 = GREATEST(from_id, to_id)Now both directions produce the same (person1, person2) pair, and person1 < person2 holds automatically because from_id != to_id.
Group by that pair and compute COUNT(*) for the number of calls and SUM(duration) for the total duration. Duplicate rows are separate calls (the three calls from 3 to 4 include two of 200), so count every row; no DISTINCT here.
The Pandas version takes the row-wise min and max of from_id and to_id as the two persons, then groups by them and aggregates the size and the sum of duration.
SELECT LEAST(from_id, to_id) AS person1,
GREATEST(from_id, to_id) AS person2,
COUNT(*) AS call_count,
SUM(duration) AS total_duration
FROM Calls
GROUP BY person1, person2;
No runs yet.