From 7b1465fc4ec429b40f75b7cb67d5c13a3ac9f696 Mon Sep 17 00:00:00 2001 From: Fortern Date: Tue, 4 Nov 2025 21:43:10 +0800 Subject: [PATCH] =?UTF-8?q?PostgreSQL=20=E7=AA=97=E5=8F=A3=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PostgreSQL/windows_fun.sql | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 PostgreSQL/windows_fun.sql diff --git a/PostgreSQL/windows_fun.sql b/PostgreSQL/windows_fun.sql new file mode 100644 index 0000000..0a4a96f --- /dev/null +++ b/PostgreSQL/windows_fun.sql @@ -0,0 +1,22 @@ +-- 窗口函数 +-- 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会不断+1,row_number()也会不断+1,id - 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; \ No newline at end of file