当前位置:Gxlcms > 数据库问题 > oracle lag与lead分析函数简介

oracle lag与lead分析函数简介

时间:2021-07-01 10:21:17 帮助过:26人阅读

10 2450.00 10 5000.00 10 1300.00 20 2975.00 20 3000.00 20 1100.00 20 800.00 20 3000.00 30 1250.00 30 1500.00 30 1600.00 30 950.00 30 2850.00 30 1250.00 ok那现在比方我有个这样的需求(我们只看sal列)我想问你2450的上一个值是多少?回答是没有 那5000的上一个值是多少?是:2450 1300的上一个值是多少呢?是:5000 Ok以此类推我想得到当前值的上一个值 就像:2450      xxx(xxx代表空)--这个值是前一列的上一个值       5000.00 2450       1300.00 5000       2975.00 1300       3000.00 2975       1100.00 3000       ...       ...       1250.00   2850 OK就这样的需求 那我们现在用SQL应该如何写呢?是的你猜对了就是用lag分析函数: select deptno, sal a, lag(sal, 1, sal) b over(order by deptno)   from scott.emp DEPTNO A B 10 2450.00 2450 --ps:这里的之所以是2450是因为lag(sal, 1, sal)我让它给了他本身的值 10 5000.00 2450 10 1300.00 5000 20 2975.00 1300 20 3000.00 2975 20 1100.00 3000 20 800.00 1100 20 3000.00 800 30 1250.00 3000 30 1500.00 1250 30 1600.00 1500 30 950.00 1600 30 2850.00 950 30 1250.00 2850 是的就这么简单你看出A列与B列之间有何联系了吧 相对A列B列是她的上一个值 关于lead她就刚好与lag相反了 select deptno, sal a, lead(sal, 1, sal) over(order by deptno) b   from scott.emp DEPTNO A B 10 2450.00 5000 10 5000.00 1300 10 1300.00 2975 20 2975.00 3000 20 3000.00 1100 20 1100.00 800 20 800.00 3000 20 3000.00 1250 30 1250.00 1500 30 1500.00 1600 30 1600.00 950 30 950.00 2850 30 2850.00 1250 30 1250.00 1250 相对A列B列是她的下一个值 另外那个偏移值1是可以随便取的如果是2那就是偏移两个值了 select deptno, sal a, lag(sal, 2,null) over(order by deptno) b   from scott.emp DEPTNO A B 10 2450.00      --注意这里是null空了 10 5000.00 10 1300.00 2450  --A列1300的上两个值是多少?2450是吧 20 2975.00 5000 20 3000.00 1300 20 1100.00 2975 20 800.00 3000 20 3000.00 1100 30 1250.00 800 30 1500.00 3000 30 1600.00 1250 30 950.00 1500 30 2850.00 1600 30 1250.00 950 OK 那其实lag,lead还可以加上分组偏移的 select deptno,        sal a,        lag(sal, 1, null) over(partition by deptno order by deptno) b   from scott.emp DEPTNO A B 10 2450.00 10 5000.00 2450 10 1300.00 5000 20 2975.00 20 3000.00 2975 20 1100.00 3000 20 800.00 1100 20 3000.00 800 30 1250.00 30 1500.00 1250 30 1600.00 1500 30 950.00 1600 30 2850.00 950 30 1250.00 2850 注意deptno不同的分组间的临界值你看明白了吧

oracle lag与lead分析函数简介

标签:order by   0.00   --   之间   数据   xxx   tno   sel   不同   

人气教程排行