【MySQL】GROUP BY 后面直接使用数字的写法(简写)

力扣题

1、题目地址

1699. 两人之间的通话次数

2、模拟表

表:Calls

Column NameType
from_idint
to_idint
durationint
  • 该表没有主键(具有唯一值的列),它可能包含重复项。
  • 该表包含 from_id 与 to_id 间的一次电话的时长。
  • from_id != to_id

3、要求

  • 编写解决方案,统计每一对用户 (person1, person2) 之间的通话次数和通话总时长,其中 person1 < person2 。
  • 以 任意顺序 返回结果表。

4、示例

输入:

Calls 表:

from_idto_idduration
1259
2111
1320
34100
34200
34200
43499

输出:

person1person2call_counttotal_duration
12270
13120
344999

解释:

用户 1 和 2 打过 2 次电话,总时长为 70 (59 + 11)。
用户 1 和 3 打过 1 次电话,总时长为 20。
用户 3 和 4 打过 4 次电话,总时长为 999 (100 + 200 + 200 + 499)。

5、代码编写

分组使用原代码(非别名)

SELECT IF(from_id < to_id, from_id, to_id) AS person1, 
	   IF(to_id > from_id, to_id, from_id) AS person2,
	   COUNT(*) AS call_count, 
	   SUM(duration) AS total_duration
FROM Calls
GROUP BY IF(from_id < to_id, from_id, to_id), IF(to_id > from_id, to_id, from_id)

分组使用别名

SELECT IF(from_id < to_id, from_id, to_id) AS person1, 
	   IF(to_id > from_id, to_id, from_id) AS person2,
	   COUNT(*) AS call_count, 
	   SUM(duration) AS total_duration
FROM Calls
GROUP BY person1, person2

分组使用数字(对应原代码查询位置,1开始递增)

SELECT IF(from_id < to_id, from_id, to_id) AS person1, 
	   IF(to_id > from_id, to_id, from_id) AS person2,
	   COUNT(*) AS call_count, 
	   SUM(duration) AS total_duration
FROM Calls
GROUP BY 1, 2
SELECT COUNT(*) AS call_count, 
	   SUM(duration) AS total_duration,
	   IF(from_id < to_id, from_id, to_id) AS person1, 
	   IF(to_id > from_id, to_id, from_id) AS person2
FROM Calls
GROUP BY 3, 4
  • 19
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值