前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Oracle SQL 基础:窗口函数(三)错行函数(lag,lead)的使用

Oracle SQL 基础:窗口函数(三)错行函数(lag,lead)的使用

作者头像
SQLplusDB
发布2022-08-19 20:56:52
1.5K0
发布2022-08-19 20:56:52
举报

今天讲一下错行函数(lag,lead)函数如何使用窗口函数。

代码语言:javascript
复制
Lag(exp_str,offset,defval) over()  
Lead(exp_str,offset,defval) over()  

    --exp_str要取的列  
    --offset取偏移后的第几行数据  
    --defval:没有符合条件的默认值

下面是表“test_student_score”的全部记录。

代码语言:javascript
复制
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         99

12行が選択されました。

先看一下不用这两个函数式的原始输出:

代码语言:javascript
复制
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”。

代码语言:javascript
复制
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 t
where t.subject_id = 3;  2    3    4    5    6

SUBJECT_ID SUBJECT_ID       LAGS      SCORE
---------- ---------- ---------- ----------
         3          3         -1         94
         3          3         94         98
         3          3         98         99

lags”就是前一位的“score”。

现在我们还要看看排在他后一位的“score”。

代码语言:javascript
复制
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 t
where 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?

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 SQL和数据库技术 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档