问题描述:
编写解决方案,统计每一对用户 (person1, person2)
之间的通话次数和通话总时长,其中 person1 < person2
。
输入:
Calls 表
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 |
输出:
person1 | person2 | call_count | total_duration | +---------+---------+------------+----------------+ | 1 | 2 | 2 | 70 | | 1 | 3 | 1 | 20 | | 3 | 4 | 4 | 999 | |
问题叙述:
用户 1 和 2 打过 2 次电话,总时长为 70 (59 + 11)。 用户 1 和 3 打过 1 次电话,总时长为 20。 用户 3 和 4 打过 4 次电话,总时长为 999 (100 + 200 + 200 + 499)。
所需函数介绍:
-- greatest(expr1, expr2, expr3, ...) 返回列表中的最大值
-- least(expr1, expr2, expr3, ...) 返回列表中的最小值
代码实现:
select
least(from_id, to_id) person1,
greatest(from_id, to_id) person2,
count(1) call_count,
sum(duration) total_duration
from
Calls
group by
least(from_id, to_id), greatest(from_id, to_id);
代码解释:
group by
least(from_id, to_id,tt), greatest(from_id, to_id)
这行代码使用 GROUP BY 子句来按 from_id 和 to_id 的最小值和最大值对结果进行分组。这样可以确保所有相关的通话记录都被归入到正确的人员对中,无论通话是由 from_id 呼叫 to_id 还是由 to_id 呼叫 from_id。