Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OVER clause in Oracle

What is the meaning of the OVER clause in Oracle?

like image 954
paweloque Avatar asked Jul 07 '09 12:07

paweloque


People also ask

What is Listagg give an example?

Basic usage of Oracle LISTAGG() function For example, the following query returns a comma-separated list of employees for each job title. In this example, the LISTAGG() function concatenates the first names of employees who have the same job title.

What does (+) mean in Oracle?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key. If there's no matching row, return null.

What is windowing clause?

A windowing clause is a set of parameters or keywords that defines the group (or window) of rows within a particular partition that will be evaluated for analytic function computation. The query in Listing 1 uses a windowing clause by default, because it uses an ORDER BY clause.

How can I delete duplicate records in Oracle?

To delete duplicate records in Oracle, start by making sure the records are actually duplicates by entering the Standard Query Language, or SQL. After entering “SQL,” search for what you want to delete, like “delete from names where name = 'Alan. '” Then, enter “commit” for this command to take effect.


1 Answers

The OVER clause specifies the partitioning, ordering and window "over which" the analytic function operates.

Example #1: calculate a moving average

AVG(amt) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)  date   amt   avg_amt =====  ====  ======= 1-Jan  10.0  10.5 2-Jan  11.0  17.0 3-Jan  30.0  17.0 4-Jan  10.0  18.0 5-Jan  14.0  12.0 

It operates over a moving window (3 rows wide) over the rows, ordered by date.

Example #2: calculate 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.

Note: for an aggregate with an OVER clause specifying a sort ORDER, the default window is UNBOUNDED PRECEDING to CURRENT ROW, so the above expression may be simplified to, with the same result:

SUM(amt) OVER (ORDER BY date) 

Example #3: calculate the maximum within each group

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.

SQL Fiddle: http://sqlfiddle.com/#!4/9eecb7d/122

like image 110
Jeffrey Kemp Avatar answered Sep 18 '22 04:09

Jeffrey Kemp