azarasi / LeetCode 1699. Number of Calls Between Two Persons

Created Thu, 14 Apr 2022 13:52:10 +0800 Modified Wed, 18 Sep 2024 14:00:22 +0000

Table: Calls

Column NameType
from_idint
to_idint
durationint

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.

Example 1:

Input: Calls table:

from_idto_idduration
1259
2111
1320
34100
34200
34200
43499

Output:

person1person2call_counttotal_duration
12270
13120
344999

Explanation: 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).

SELECT person1,
       person2,
       count(*)      call_count,
       sum(duration) total_duration
FROM (SELECT IF(from_id > to_id, to_id, from_id) person1,
             IF(from_id > to_id, from_id, to_id) person2,
             duration
      FROM Calls) c
GROUP BY person1,
         person2