1
0
Files
sql-study/PostgreSQL/windows_fun.sql
2025-11-05 03:52:35 +08:00

22 lines
1.1 KiB
SQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- 窗口函数
-- row_number(): 对相等的值【不区分】相当于行号相等的值对应的排名不同序号从1到n连续
-- rank(): 相等的值排名相同但若有相等的值则序号从1到n不连续。符合一般人思维中的排名
-- dense_rank(): 对相等的值排名相同但序号从1到n连续
-- 先按num分区每个区内按id排序
select id, num, id - row_number() over (partition by num order by id) as rnk
from employee;
-- 找出所有至少连续出现三次的数字
-- 先按num分区每个区内按id排序
-- 一个分区内如果数字连续那么id会不断+1row_number()也会不断+1id - row_number()差值不变
-- 在按照id - row_number()聚合使用count(*)统计count(*)的结果就是连续出现的次数
select r.num, r.rnk, count(*)
from (select num, id - row_number() over (partition by num order by id) as rnk from employee) as r
group by r.num, r.rnk;
select distinct r.num as ConsecutiveNums
from (select num, id - row_number() over (partition by num order by id) as rnk from employee) as r
group by r.num, r.rnk
having count(*) >= 3
limit 1;