-
leetcode - 1699. Number of Calls Between Two PersonsSQL 문제풀이 2022. 8. 24. 16:53
난이도 : Medium
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_idWrite 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_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 | +---------+-------+----------+ Output: +---------+---------+------------+----------------+ | person1 | person2 | call_count | total_duration | +---------+---------+------------+----------------+ | 1 | 2 | 2 | 70 | | 1 | 3 | 1 | 20 | | 3 | 4 | 4 | 999 | +---------+---------+------------+----------------+ 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).WITH sub AS ( SELECT CASE WHEN from_id < to_id THEN from_id ELSE to_id END person1 , CASE WHEN from_id > to_id THEN from_id ELSE to_id END person2 , duration FROM Calls ) SELECT person1 , person2 , COUNT(*) call_count , SUM(duration) total_duration FROM sub GROUP BY 1, 2Accepted (63.25%)
'SQL 문제풀이' 카테고리의 다른 글
leetcode - 1715. Count Apples and Oranges (0) 2022.08.24 leetcode - 1709. Biggest Window Between Visits (0) 2022.08.24 leetcode - 1613. Find the Missing IDs (0) 2022.08.19 leetcode - 1596. The Most Frequently Ordered Products for Each Customer (0) 2022.08.19 leetcode - 1555. Bank Account Summary (0) 2022.08.19