FIRST和LAST函数
功能:获取首行和尾行(可以有并列的情况)的非排序字段的值
语法:
aggregate_function KEEP (DENSE_RANK {FIRST |LAST }ORDERBY expr [DESC | ASC] [NULLSFIRST | LAST])
OVER (query_partition_clause)
使用说明:
①first和last函数有over子句就是分析函数,没有就是聚合函数。
②函数的参数必须是数字类型(或者其他类型可转为数字类型),返回相同类型
③aggregate_function可以是MIN,MAX,SUM,AVG,COUNT,VARIANCE,STDDEV
示例:
用表:SELECT *FROM hr.employees;
当作聚合函数用:按部门分组,按提成比例排序,取最大最小薪水
SELECT department_id
,MIN(salary)keep(dense_rankFIRST ORDER BY commission_pct) "Worst"
,MAX(salary)keep(dense_rankLAST ORDER BY commission_pct) "Best"
FROM hr.employees
GROUP BY department_id
ORDER BY department_id;
当作分析函数用:按部门分组,按提成比例排序,取最大最小薪水
SELECT last_name
,department_id
,salary
,MIN(salary)keep(dense_rankFIRSTORDER BY commission_pct)over(PARTITION BY department_id)"Worst"
,MAX(salary)keep(dense_rankLASTORDER BY commission_pct)over(PARTITION BY department_id)"Best"
FROM hr.employees
ORDER BY department_id,salary, last_name;
first_value()和last_value()函数
功能:FIRST_VALUE是一个返回一组排序值后的第一个值的分析函数。
语法:
【推荐】FIRST_VALUE( expr ) [RESPECT |IGNOREN ULLS] OVER ( analytic_clause )
【老版本】FIRST_VALUE( expr [RESPECT |IGNOREN ULLS])OVER ( analytic_clause )
使用说明:
①在计算时,默认考虑null,除非指定忽略null值。
示例:
60部门按照薪资排序,取第一行、当前行、最后一行
SELECT department_id
,employee_id
,last_name
,salary
,first_value(last_name) over(ORDER BY salary rows unbounded preceding)AS fv
,last_value(last_name) over(ORDER BY salaryROWS BETWEEN unbounded PRECEDING AND CURRENTROW ) AS lv
,last_value(last_name) over(ORDER BY salaryROWS BETWEEN unbounded PRECEDING AND UNBOUNDED FOLLOWING ) AS lv
FROM hr.employees
WHERE department_id =60;