您的位置:首页 > 数据库 > Oracle

oracle keep(first/last)

2010-05-18 11:02 183 查看
先看一段ORACLE官方文档

http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/analysis.htm#25806:

FIRST/LAST Functions

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
,
***G
,
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开始即可

FIRST/LAST Syntax

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子句可以采取多种表现形式

Returns the row ranked first using DENSE_RANK

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;



DEPTNOENAMEEMPNOHIREDATESALmin_sal
10CLARK77821981-06-092450.002450
10KING78391981-11-175000.002450
10MILLER79341982-01-231300.002450
20yang_ping73891980-12-172700.00800
20SMITH73691980-12-17800.00800
20ADAMS78761987-05-231100.00800
20FORD 79021981-12-033000.00800
20SCOTT77881987-04-194000.00800
20JONES75661981-02-222975.00800
30ALLEN74991981-02-201600.001600
30BLAKE76981981-05-012850.001600
30MARTIN76541981-09-281250.001600
30JAMES79001981-12-03950.001600
30TURNER78441981-12-031500.001600
30WARD75211981-02-221250.001600
查看结果分析:红色部分,2个入厂日期一样,同时取工资最低得到800



再看一个:计算部门平均工资,并且入工厂最早的最低的工资

SQL>select deptno,avg(sal) as sal,

min(sal)KEEP (dense_rank FIRST ORDER BY hiredate) AS min_sal
from emp group by deptno;



DEPTNOSALMIN_SAL
103437.52450
202645.833800
301566.6671600
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: