Number Of Calls Between Two Persons Problem


Description

LeetCode Problem 1699.

Table: Calls

1
2
3
4
5
6
7
8
9
10
+-------------+---------+
| 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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).


MySQL Solution

1
2
3
4
5
6
7
8
9
10
11
select from_id as person1,to_id as person2,
    count(duration) as call_count, sum(duration) as total_duration
from (select * 
      from Calls 
      
      union all
      
      select to_id, from_id, duration 
      from Calls) t1
where from_id < to_id
group by person1, person2




Related Posts

Biggest Window Between Visits Problem

LeetCode 1709. Write an SQL query that will, for each...

Number Of Calls Between Two Persons Problem

LeetCode 1699. Write an SQL query to report the number...

Daily Leads And Partners Problem

LeetCode 1693. Write an SQL query that will, for each...

Product's Worth Over Invoices Problem

LeetCode 1677. Write an SQL query that will, for all...

Fix Names In A Table Problem

LeetCode 1667. Write an SQL query to fix the names...

Invalid Tweets Problem

LeetCode 1683. Write an SQL query to find the IDs...