-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNumber of Calls Between Two Persons 7-10-22
More file actions
75 lines (55 loc) · 2.22 KB
/
Number of Calls Between Two Persons 7-10-22
File metadata and controls
75 lines (55 loc) · 2.22 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
LINK -------- https://www.codingninjas.com/codestudio/problems/number-of-calls-between-two-persons_2181135?topList=top-100-sql-problems&leftPanelTab=0
Problem Statement
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).
------------------------------ solution 1 -----------------------------
SELECT
LEAST (from_id, to_id) person1 ,
GREATEST(from_id,to_id) person2,
COUNT(*) call_count,
SUM(duration) total_duration
FROM calls
GROUP BY 1,2
-------------------------- solution 2 ------------------------
select case
when from_id < to_id then from_id else to_id end as person1,
case when to_id > from_id then to_id else from_id end as person2,
count(*) as call_count,
sum(duration) as total_duration
from Calls
group by 1, 2