当前位置:网站首页>SQL练习 2022/7/2
SQL练习 2022/7/2
2022-08-04 05:28:00 【Provence°_博】
SQL练习 2022/7/2
180. 连续出现的数字
题干
代码思路
- 多表连接
select distinct l1.Num as ConsecutiveNums
from Logs l1,Logs l2,Logs l3
where l1.Id+1=l2.id and l2.id+1=l3.id
and l1.Num =l2.Num and l2.Num=l3.Num
- 窗口函数
目前没看懂~~~
select
distinct num as 'ConsecutiveNums'
from (
select
num, id - cast(rank() over(partition by num order by id) as signed) as 'g'
from Logs
) as t
group by num, g
having count(1) >= 3
- 用开窗做, 核心是 使用 dense_rank() 对nums 和 id 进行排序, 得到排名列rk, 如果连续, 则 rk 列 与 id 列的差应该为一样的值. 之后再用一次group by统计数量即可. 需要注意的是 rk 为无符号数, 需要做一次转化, 否则会出现错误. sql 如下:
with t1 as
( select
num,
id - cast(dense_rank() over (order by num,id) as signed Integer) tmp
from logs
)
select
distinct num ConsecutiveNums
from t1
group by tmp, num
having count(1) > 2;
使用 lead 开窗 的核心为 对 num 进行分组 并 对num进行分组并对 组内的 id 进行排序, 去排序后移两位的id, 如果其等于2, 则表示连续.sql如下:
with tmp as (
select num,
lead(id, 2) over (partition by num order by id ) - id sub
from logs
)
select distinct num ConsecutiveNums from tmp where sub = 2 ;
emmmm开窗还是不懂啊
178. 分数排名
题干
代码思路
- dense_rank的窗口函数
窗口函数用法:<窗口函数> OVER ( [PARTITION BY <列清单> ] ORDER BY <排序用列清单> )DENSE_RANK()
:
这就是题目中所用到的函数,在计算排序时,若存在相同位次,不会跳过之后的位次。
例如,有3条排在第1位时,排序为:1,1,1,2·····
select score ,dense_rank() over(order by score desc) as rankfrom Scores order by score desc
- 统计比每一个成绩大的不同成绩数量。就可以统计出排名了
select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank
from Scores a
order by a.Score DESC
边栏推荐
猜你喜欢
随机推荐
Swoole学习(一)
ISCC-2022
Embedded system driver primary [4] - under the basis of character device driver _ concurrency control
实际开发中左菜单自定义图标点击切换
php将多维数据保存进json文件
【树 图 科 技 头 条】2022年6月27日 星期一 今年ETH2.0无望
Lombok的一些使用心得
对象存储-分布式文件系统-MinIO-1:概念
JS深复制对象方法(深拷贝)
对象存储-分布式文件系统-MinIO-3:MinIo Client(mc)
自动化运维工具Ansible(2)ad-hoc
大龄程序员的心理建设
EventBus源码分析
flink-sql所有语法详解
二月、三月校招面试复盘总结(二)
Zend FrameWork RCE1
程序、进程、线程、协程的概念及区别
Kubernetes基本入门-元数据资源(四)
即时通讯网 即时通讯音视频开发
Commons Collections2