first_value和last_value 是用来去分析函数窗口中对应列的第一个值和最后一个值的函数。
语法如下:
first_value(col [ignore NULLS]) over([PARTITION BY col] [ORDER BY sal] [windows]) last_value(col [ignore NULLS]) over([PARTITION BY col] [ORDER BY sal] [windows]) --col : 表示选取的列 --ignore NULLS :表示忽略空值 --PARTITION BY :表示分组 --ORDER BY :表示排序 --windows :表示窗口,默认值是(RANGE UNBOUNDED PRECEDING AND CURRENT ROW)从第一行到当前行 --windows :常用值(ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)从第一行到最后一行
示例1:
SELECT first_value(comm ) over() firstval, last_value(comm ) over() lastval, e.* FROM emp e
结果:
示例2:
SELECT first_value(comm ) over(partition by deptno) firstval, last_value(comm ) over(partition by deptno) lastval, e.* FROM emp e
结果:
示例3:
SELECT first_value(comm ) over(partition by deptno order by sal) firstval, last_value(comm ) over(partition by deptno order by sal) lastval, e.* FROM emp e
结果:
示例4:
SELECT first_value(comm ignore nulls) over(partition by deptno order by sal) firstval, last_value(comm ignore nulls) over(partition by deptno order by sal) lastval, e.* FROM emp e
结果:
示例5:
SELECT first_value(sal ignore nulls) over(partition by deptno order by sal) firstval, last_value(sal ignore nulls) over(partition by deptno order by sal) lastval, e.* FROM emp e; SELECT first_value(sal ignore nulls) over(partition by deptno order by sal) firstval, last_value(sal ignore nulls) over(partition by deptno order by sal ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) lastval, e.* FROM emp e
结果:
第一个sql结果:
第二个sql结果: