OVER clause in Oracle

前端 未结 3 1518
面向向阳花
面向向阳花 2020-11-29 19:16

What is the meaning of the OVER clause in Oracle?

相关标签:
3条回答
  • 2020-11-29 19:21

    It's part of the Oracle analytic functions.

    0 讨论(0)
  • 2020-11-29 19:31

    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.

    0 讨论(0)
  • 2020-11-29 19:42

    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  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.

    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.

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

    0 讨论(0)
提交回复
热议问题