-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Calls Between Two Persons
57 lines (46 loc) · 1.53 KB
/
Number of Calls Between Two Persons
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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).
Answer:
WITH CALL_LOGS AS (
SELECT FROM_ID,
TO_ID,
DURATION
FROM CALLS
UNION ALL
SELECT TO_ID,
FROM_ID,
DURATION
FROM CALLS
)
SELECT FROM_ID AS PERSON1,
TO_ID AS PERSON2,
COUNT(*) AS CALL_COUNT,
SUM(DURATION) AS TOTAL_DURATION
FROM CALL_LOGS
WHERE FROM_ID < TO_ID
GROUP BY FROM_ID, TO_ID
;