You have a Calls table that contains information about phone calls between different people. Each row represents a call with the caller ID (from_id), receiver ID (to_id), and the duration of the call.
Task: Write a SQL query to find the number of calls and total call duration between each pair of distinct persons, where the pairs are ordered such that person1 < person2.
Key Requirements:
- Group calls between the same two people regardless of who initiated the call
- Ensure
person1 < person2in the result to avoid duplicate pairs - Return the count of calls and sum of durations for each pair
Table Schema
| Column Name | Type | Description |
|---|---|---|
from_id
|
int | ID of the person who made the call |
to_id
|
int | ID of the person who received the call |
duration
|
int | Duration of the call in minutes |
Input & Output
| 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 | 100 |
| person1 | person2 | call_count | total_duration |
|---|---|---|---|
| 1 | 2 | 2 | 70 |
| 1 | 3 | 1 | 20 |
| 3 | 4 | 4 | 600 |
The query groups calls between the same two people regardless of who initiated the call. Person 1 and 2 had 2 calls (59+11=70 total minutes). Person 1 and 3 had 1 call (20 minutes). Person 3 and 4 had 4 calls (100+200+200+100=600 total minutes).
| from_id | to_id | duration |
|---|---|---|
| 1 | 2 | 30 |
| 3 | 4 | 45 |
| 5 | 6 | 15 |
| person1 | person2 | call_count | total_duration |
|---|---|---|---|
| 1 | 2 | 1 | 30 |
| 3 | 4 | 1 | 45 |
| 5 | 6 | 1 | 15 |
Each pair of people had exactly one call, so call_count is 1 for each pair and total_duration equals the duration of their single call.
Constraints
-
from_id != to_idfor all rows -
1 ≤ from_id, to_id ≤ 1000 -
1 ≤ duration ≤ 1000 - The table may contain duplicate rows