leetcode 1811. Find Interview Candidates---窗口函数相减

Find Interview Candidates
题目分析:题目的问题是
在这里插入图片描述
翻译过来的意思就是:找出连续三场赢得奖牌的人或者赢得了三个金牌的人。给了contests和users两张表。
首先第一个,找出赢得了三个金牌的人很简单,对gold_medel那一行进行group by即可

select gold_medal from Contests group by gold_medal having count(*) >= 3;

接着第二点,连续三场获得奖牌,这个就有点意思,首先contests表给的是金牌银牌铜牌三个都有的,所以需要列转行,使用union all。思路与这题完全相同leetcode1783 列转行

select contest_id,gold_medal id from Contests union all 
select contest_id,silver_medal from Contests union all
select contest_id,bronze_medal from Contests order by id,contest_id

接着采用row_number()进行编号相减,思路与这一题完全相同 leetcode 1258 窗口函数的妙用

select distinct id from (
select contest_id,contest_id-rr cr,id from (
select contest_id,row_number() over(partition by id order by contest_id) rr,id from (
select contest_id,gold_medal id from Contests union all 
select contest_id,silver_medal from Contests union all
select contest_id,bronze_medal from Contests order by id,contest_id) F1) F2) F3 group by id,cr having count(*) >= 3

对上面的结果进行inner join得到最终结果

select U.name,U.mail from Users U inner join (select gold_medal id from Contests group by gold_medal having count(*) >= 3 union  
select distinct id from (
select contest_id,contest_id-rr cr,id from (
select contest_id,row_number() over(partition by id order by contest_id) rr,id from (
select contest_id,gold_medal id from Contests union all 
select contest_id,silver_medal from Contests union all
select contest_id,bronze_medal from Contests order by id,contest_id) F1) F2) F3 group by id,cr having count(*) >= 3) F on U.user_id = F.id

提交结果如下:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值