先看一段ORACLE官方文档
The FIRST/LAST
aggregate functions allow you to return the result of an aggregate applied over a set of rows that rank as the first or last with respect to a given order specification. FIRST/LAST
lets you order on column A but return an result of an aggregate applied on column B. This is valuable because it avoids the need for a self-join or subquery, thus improving performance. These functions begin with a tiebreaker function, which is a regular aggregate function (MIN
, MAX
, SUM
, AVG
, COUNT
, VARIANCE
, STDDEV
) that produces the return value. The tiebreaker function is performed on the set rows (1 or more rows) that rank as first or last respect to the order specification to return a single value.
To specify the ordering used within each group, the FIRST/LAST
functions add a new clause starting with the word KEEP
.
大意是说FIRST/LAST函数按照某个字段排序后取得第一行或者最后一行,FIRST/LAST聚集函数可以按A列排序,B列聚集,避免了自连接和子查询.分组聚合函数(min,max....)位于FIRST/LAST函数之前产生多行结果集,并且按照排序返回FIRST/LAST单个值.
要指定在每个组的顺序,FIRST/LAST函数之前加上以关键字KEEP开始即可
These functions have the following syntax:
aggregate_function KEEP
( DENSE_RANK LAST ORDER BY
expr [ DESC | ASC ] [NULLS { FIRST | LAST }]
[, expr [ DESC | ASC ] [NULLS { FIRST | LAST }]]...)
[OVER query_partitioning_clause]
Note that the ORDER
BY
clause can take multiple expressions.请注意在ORDER BY子句可以采取多种表现形式
2种取值:
DENSE_RANK FIRST
DENSE_RANK LAST
在keep (DENSE_RANK first ORDER BY sl) 结果集中再取max、min的例子。
例子如下:oracle分析函数中,keep and over的区别
公司部门中入厂时间最早的员工的薪水最小的是多少
SQL>SELECT deptno,ename,empno,sal,
MIN(sal) KEEP (dense_rank FIRST ORDER BY hiredate) over (PARTITION BY deptno) "min_sal"
FROM emp;
DEPTNO | ENAME | EMPNO | HIREDATE | SAL | min_sal |
10 | CLARK | 7782 | 1981-06-09 | 2450.00 | 2450 |
10 | KING | 7839 | 1981-11-17 | 5000.00 | 2450 |
10 | MILLER | 7934 | 1982-01-23 | 1300.00 | 2450 |
20 | yang_ping | 7389 | 1980-12-17 | 2700.00 | 800 |
20 | SMITH | 7369 | 1980-12-17 | 800.00 | 800 |
20 | ADAMS | 7876 | 1987-05-23 | 1100.00 | 800 |
20 | FORD | 7902 | 1981-12-03 | 3000.00 | 800 |
20 | SCOTT | 7788 | 1987-04-19 | 4000.00 | 800 |
20 | JONES | 7566 | 1981-02-22 | 2975.00 | 800 |
30 | ALLEN | 7499 | 1981-02-20 | 1600.00 | 1600 |
30 | BLAKE | 7698 | 1981-05-01 | 2850.00 | 1600 |
30 | MARTIN | 7654 | 1981-09-28 | 1250.00 | 1600 |
30 | JAMES | 7900 | 1981-12-03 | 950.00 | 1600 |
30 | TURNER | 7844 | 1981-12-03 | 1500.00 | 1600 |
30 | WARD | 7521 | 1981-02-22 | 1250.00 | 1600 |
再看一个:计算部门平均工资,并且入工厂最早的最低的工资
SQL>select deptno,avg(sal) as sal,
min(sal)KEEP (dense_rank FIRST ORDER BY hiredate) AS min_sal
from emp group by deptno;
DEPTNO | SAL | MIN_SAL |
10 | 3437.5 | 2450 |
20 | 2645.833 | 800 |
30 | 1566.667 | 1600 |