SQL> edit
1 select first_name,department_id,count(*) over(partition by department_id) as cnt
2 from employees
3* order by 2
SQL> /
FIRST_NAME DEPARTMENT_ID CNT
-------------------- ------------- ----------
Jennifer 10 1
Michael 20 2
Pat 20 2
Den 30 6
Alexander 30 6
Shelli 30 6
Sigal 30 6
Guy 30 6
Karen 30 6
Susan 40 1
Matthew 50 45
。。。。。。。。。。
如上结果所示:对于同一个部门(同一个分区)的每个员工的cnt值相同,这是由于在遇到新部门之前不会重置聚集。
1 select department_id,first_name,hire_date,salary,
2 sum(salary) over(partition by department_id) as total1,
3 sum(salary) over() as total2,
4 sum(salary) over(order by hire_date range between unbounded preceding and current row) as running_total
5 from employees
6* where department_id=30
1 select department_id,first_name,salary,
2 sum(salary) over (order by hire_date range between unbounded preceding and current row) as run_total1,
3 sum(salary) over(order by hire_date rows between 1 preceding and current row) as run_total2,
4 sum(salary) over(order by hire_date range between current row and unbounded following) as run_total3,
5 sum(salary) over(order by hire_date rows between current row and 1 following) as run_total4
6 from employees
7* where department_id=30
SQL> /
DEPARTMENT_ID FIRST_NAME SALARY RUN_TOTAL1 RUN_TOTAL2 RUN_TOTAL3
------------- -------------------- ---------- ---------- ---------- ----------
RUN_TOTAL4
----------
30 Den 11000 11000 11000 24900
14100
30 Alexander 3100 14100 14100 13900
5900
30 Sigal 2800 16900 5900 10800
5700
rangebetweencurrentrowandunbounded
following 指定计算从当前行开始,包括它后面的所有行;
rowsbetweencurrentrowand1
following 指定计算当前行和它后面的一行;
最后一个例子,展示 了框架字句对查询输出的影响,请看下面查询:
1 select first_name,salary,min(salary) over(order by salary) min1,
2 max(salary) over(order by salary) max1,
3 min(salary) over(order by salary range between unbounded preceding and unbounded following) min2,
4 max(salary) over(order by salary range between unbounded preceding and unbounded following) max2,
5 min(salary) over(order by salary range between current row and current row) min3,
6 max(salary) over(order by salary range between current row and current row) max3,
7 max(salary) over(order by salary rows between 3 preceding and 3 following) max4
8* from employees
SQL> /
FIRST_NAME SALARY MIN1 MAX1 MIN2 MAX2
-------------------- ---------- ---------- ---------- ---------- ----------
MIN3 MAX3 MAX4
---------- ---------- ----------
TJ 2100 2100 2100 2100 24000
2100 2100 2400
Steven 2200 2100 2200 2100 24000
2200 2200 2400
Hazel 2200 2100 2200 2100 24000
2200 2200 2500