MAX 查找组中表达式的最大值 MAX(COL ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
MIN 查找组中表达式的最小值 MIN(COL ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
AVG 计算组中表达式的平均值 AVG(COL ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
SUM 计算组中表达式的累积和 SUM(COL ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
简单测试:
SQL> select deptno,
2 ename,
3 sal,
4 max(sal) over(partition by deptno order by sal) max_sal_asc,
5 max(sal) over(partition by deptno order by sal desc) max_sal_desc,
6 min(sal) over(partition by deptno order by sal) min_sal,
7 avg(sal) over(partition by deptno order by sal) avg_sal,
8 sum(sal) over(partition by deptno order by sal) sum_sal
9 from emp;
DEPTNO ENAME SAL MAX_SAL_ASC MAX_SAL_DESC MIN_SAL AVG_SAL SUM_SAL
---------- ---------- ---------- ----------- ------------ ---------- ---------- ----------
10 MILLER 1300 1300 5000 1300 1300 1300
10 CLARK 2450 2450 5000 1300 1875 3750
10 KING 5000 5000 5000 1300 2916.66667 8750
20 SMITH 800 800 3000 800 800 800
20 JONES 2975 2975 3000 800 1887.5 3775
20 FORD 3000 3000 3000 800 2258.33333 6775
30 JAMES 950 950 2850 950 950 950
30 WARD 1250 1250 2850 950 1150 3450
30 MARTIN 1250 1250 2850 950 1150 3450
30 TURNER 1500 1500 2850 950 1237.5 4950
30 ALLEN 1600 1600 2850 950 1310 6550
30 BLAKE 2850 2850 2850 950 1566.66667 9400
已选择12行。
上面例子说明:
max(sal) over(partition by deptno order by sal),当既有分组又有排序时,因为按sal升序,只要deptno和sal没有重复的行,每一行的sal都是该行的最大值;
如果是按sal降序排序,则第一行即为最大的行了,之后也以第一行作为max值了。
min(sal) over(partition by deptno order by sal),按升序排序,第一行已经是整个分组里最小的了,所以该分组内min值都为第一行的值;
avg(sal) over(partition by deptno order by sal),按排序顺序,每一行的avg,都为截止到当前行为止,该分组的avg值;
sum(sal) over(partition by deptno order by sal),按排序顺序,每一行的sum,都为截止到当前行为止,该分组的sum值。