欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Oracle分析函数FIRST_VALUE、LAST_VALUE

程序员文章站 2022-03-23 14:28:35
FIRST_VALUE、LAST_VALUE分析函数可以按照特定分组和排序取出组内首尾值,语法FIRST_VALUE { (expr) [ {RESPECT | IGNORE} NULLS ] | (expr [ {RESPECT | IGNORE} NULLS ]) } OVER (analyti... ......

first_value、last_value分析函数可以按照特定分组和排序取出组内首尾值,语法

first_value 
  { (expr) [ {respect | ignore} nulls ]
  | (expr [ {respect | ignore} nulls ])
  }
  over (analytic_clause)

测试下

10:48:07 scott@study> select empno,
10:48:15   2         deptno,
10:48:15   3         sal,
10:48:15   4         first_value(sal) ignore nulls over(partition by deptno order by sal) as lowest_in_dept,
10:48:15   5         first_value(sal) ignore nulls over(partition by deptno order by sal rows 1 preceding) as preceding_in_dept,
10:48:15   6         last_value(sal) ignore nulls over(partition by deptno order by sal) as highest_in_dept,
10:48:15   7         last_value(sal) ignore nulls over(partition by deptno order by sal rows between unbounded preceding and unbounded following) as highest_in_dept
10:48:15   8    from emp;

     empno     deptno        sal lowest_in_dept preceding_in_dept highest_in_dept highest_in_dept
---------- ---------- ---------- -------------- ----------------- --------------- ---------------
      7934         10       1300           1300              1300            1300            5000
      7782         10       2450           1300              1300            2450            5000
      7839         10       5000           1300              2450            5000            5000
      7369         20        800            800               800             800            3000
      7876         20       1100            800               800            1100            3000
      7566         20       2975            800              1100            2975            3000
      7788         20       3000            800              2975            3000            3000
      7902         20       3000            800              3000            3000            3000
      7900         30        950            950               950             950            2850
      7654         30       1250            950               950            1250            2850
      7521         30       1250            950              1250            1250            2850
      7844         30       1500            950              1250            1500            2850
      7499         30       1600            950              1500            1600            2850
      7698         30       2850            950              1600            2850            2850

14 rows selected.

elapsed: 00:00:00.00
10:48:17 scott@study> 

last_value的默认写法结果不符合预期,是因为默认的开窗语句"range between unbounded preceding and current row",所以需要显性写出正确的开窗语句