说明:题目来源为力扣(LeetCode),本文主要记录笔者解题思路及发现的一些奇妙的解题思路
表:Calls
+-------------+---------+| Column Name | Type |+-------------+---------+| from_id | int || to_id | int || duration | int |+-------------+---------+
该表没有主键,可能存在重复项。
该表包含 from_id 与 to_id 间的一次电话的时长。
from_id != to_id
编写 SQL 语句,查询每一对用户 (person1, person2) 之间的通话次数和通话总时长,其中 person1 < person2 。
以 任意顺序 返回结果表。
查询结果格式如下示例所示。
示例 1:
输入:
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)。
常规解题:解题关键是用户对判断,使用if判断实现
select from_id as person1 ,to_id as person2,count(1) as call_count,sum(duration) as total_durationfrom(select if(from_id>to_id,to_id,from_id) as from_id,if(from_id>to_id,from_id,to_id) as to_id,durationfrom calls) t1group by from_id,to_id
奇妙思路:直接使用least和greatest实现用户对分组
selectfrom_id as person1,to_id as person2,count(1) as call_count,sum(duration) as total_durationfrom callsgroup by least(from_id, to_id),greatest(from_id, to_id)

文章转载自蔓蔓的数据空间,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




