What is the meaning of the OVER clause in Oracle?
+1
A:
You can use it to transform some aggregate functions into analytic:
SELECT MAX(date)
FROM mytable
will return 1
row with a single maximum,
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
will return all rows with a running maximum.
Quassnoi
2009-07-07 12:50:16
+4
A:
The OVER clause specifies the partitioning, ordering & window "over which" the analytic function operates.
For example, this calculates a moving average:
AVG(amt) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
date amt avg_amt
===== ==== =======
1-Jan 10.0 7.0
2-Jan 11.0 17.0
3-Jan 30.0 17.0
4-Jan 10.0 18.0
5-Jan 14.0 8.0
It operates over a moving window (3 rows wide) over the rows, ordered by date.
This calculates a running balance:
SUM(amt) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
date amt sum_amt
===== ==== =======
1-Jan 10.0 10.0
2-Jan 11.0 21.0
3-Jan 30.0 51.0
4-Jan 10.0 61.0
5-Jan 14.0 75.0
It operates over a window that includes the current row and all prior rows.
This calculates the maximum, separately for each "dept":
MAX(amt) OVER (PARTITION BY dept)
dept amt max_amt
==== ==== =======
ACCT 5.0 7.0
ACCT 7.0 7.0
ACCT 6.0 7.0
MRKT 10.0 11.0
MRKT 11.0 11.0
SLES 2.0 2.0
It operates over a window that includes all rows for a particular dept.
Jeffrey Kemp
2009-07-07 15:54:17