Leetcode 1501题: Countries You Can Safely Invest In

题目描述

这道题,相对来说比较复杂,总共需要用到3张表,以及多次子查询。下面是3张表的信息。

Person表

±---------------±--------+
| Column Name | Type |
±---------------±--------+
| id | int |
| name | varchar |
| phone_number | varchar |
±---------------±--------+
总共3列,分别是用户id,用户姓名以及用户的电话号码,其中电话号码的前3位为地区号。

Country表

±---------------±--------+
| Column Name | Type |
±---------------±--------+
| name | varchar |
| country_code | varchar |
±---------------±--------+
总共2列,分别是国家名称以及国家代号,同上面的电话号码地区号。

Calls 表

±------------±-----+
| Column Name | Type |
±------------±-----+
| caller_id | int |
| callee_id | int |
| duration | int |
±------------±-----+
总共3列,分别是电话发起方的id,电话接收方的id以及通话时长。

题目要求:找到平均通话时长大于global平均通话时长的那个国家的名称。

My Solution

1.因为duration需要考虑通话双方,因此,第一步我们需要将Calls表中的拨打和接收方信息合并成一列,duration单独一列。这里我使用的是mysql中的union all方法。

2.将上述得到的表的用户id转换得到对应的区号,这里需要需要将第1步得到的表与Person表进行左连接,同时在获取区号的时候,我们需要用到字符串的截取,使用left(phone_number,3)

3.将2步得到结果表按照区号进行group by,并计算平均通话时长sum(duration)/count(*)

4.另外构建一张子查询表用于计算global通话时长。

5.使用where条件筛选出3表中平均通话时长大于从4表中得到的global通话时长的国家区号

6.将5的到的结果与Country表再进行左连接,并选取对应的国家名称。

完整代码

select name country
 from 
(select country_code from (select country_code,sum(duration)/count(*) avg from (select country_code,duration from (select caller_id calleree_id,duration from Calls union all select callee_id calleree_id,duration from Calls) as t0 left join (select id,left(phone_number,3) country_code from Person) as t1 on t0.calleree_id=t1.id) as t2 group by country_code) as t3,(select sum(duration)*2/(count(*)*2) global_avg from Calls) as t4 where t3.avg>t4.global_avg) as t5
left join
Country
on t5.country_code=Country.country_code;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值