编者按:
本文作者系Scott(中文名陈晓辉),现任大连华信资深分析师 ,ORACLE数据库专家,曾就职于甲骨文中国。个人主页:segmentfault.com/u/db_perf ,经其本人授权发布。
【免责声明】本公众号文章仅代表个人观点,与任何公司无关。

Oracle SQL 基础:窗口函数(二)RANK函数如何使用窗口函数
今天讲一下错行函数(lag,lead)函数如何使用窗口函数。
Lag(exp_str,offset,defval) over() Lead(exp_str,offset,defval) over() --exp_str要取的列 --offset取偏移后的第几行数据 --defval:没有符合条件的默认值
下面是表“test_student_score”的全部记录。
SQL> select t.* from test_student_score t;STUDENT_ID SUBJECT_ID SCORE---------- ---------- ---------- 1 1 90 3 4 91 3 1 93 3 3 94 3 2 94 1 4 95 2 2 95 2 4 97 2 1 98 1 2 98 2 3 98 1 3 9912行が選択されました。
先看一下不用这两个函数式的原始输出:
SQL> select * from test_student_score t where t.subject_id = 3;STUDENT_ID SUBJECT_ID SCORE---------- ---------- ---------- 1 3 99 2 3 98 3 3 94
下面我们不仅要看“score”,还要看看排在他前一位的“score”。
SQL> select t.subject_id, t.subject_id, lag(t.score, 1, -1) over(order by t.score) as lags, t.score from test_student_score twhere t.subject_id = 3; 2 3 4 5 6SUBJECT_ID SUBJECT_ID LAGS SCORE---------- ---------- ---------- ---------- 3 3 -1 94 3 3 94 98 3 3 98 99
“lags”就是前一位的“score”。
现在我们还要看看排在他后一位的“score”。
SQL> select t.subject_id, t.subject_id, lag(t.score, 1, -1) over(order by t.score) as lags, t.score, lead(t.score, 1, -1) over(order by t.score) as leads from test_student_score twhere t.subject_id = 3;SUBJECT_ID SUBJECT_ID LAGS SCORE LEADS---------- ---------- ---------- ---------- ---------- 3 3 -1 94 98 3 3 94 98 99 3 3 98 99 -1
“leads”就是后一位的“score”。
Do you get it?
后续文章更加精彩,欢迎关注本公众号或访问【阅读原文】。
——End——
专注于技术不限于技术!
用碎片化的时间,一点一滴地提高数据库技术和个人能力。
欢迎关注!
Oracle SQL 基础(学习SQL的写法):
最后修改时间:2021-04-25 07:31:04
文章转载自Oracle数据库技术,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




