返回介绍

solution / 1600-1699 / 1699.Number of Calls Between Two Persons / README_EN

发布于 2024-06-17 01:03:15 字数 3091 浏览 0 评论 0 收藏 0

1699. Number of Calls Between Two Persons

中文文档

Description

Table: Calls

+-------------+---------+
| Column Name | Type  |
+-------------+---------+
| from_id   | int   |
| to_id     | int   |
| duration  | int   |
+-------------+---------+
This table does not have a primary key (column with unique values), it may contain duplicates.
This table contains the duration of a phone call between from_id and to_id.
from_id != to_id

 

Write a solution 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 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).

Solutions

Solution 1: Grouping and Summing

We can use the if function or the least and greatest functions to convert from_id and to_id into person1 and person2, and then group by person1 and person2 and sum the values.

# Write your MySQL query statement below
SELECT
  IF(from_id < to_id, from_id, to_id) AS person1,
  IF(from_id < to_id, to_id, from_id) AS person2,
  COUNT(1) AS call_count,
  SUM(duration) AS total_duration
FROM Calls
GROUP BY 1, 2;
# Write your MySQL query statement below
SELECT
  LEAST(from_id, to_id) AS person1,
  GREATEST(from_id, to_id) AS person2,
  COUNT(1) AS call_count,
  SUM(duration) AS total_duration
FROM Calls
GROUP BY 1, 2;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文