在Oracle中,OVER函数通常与分析函数一起使用,以便在结果集中执行窗口函数计算。语法如下:
<analytic_function> OVER (
[PARTITION BY <column_list>]
[ORDER BY <column_list>]
[window_clause]
)
其中,<analytic_function>
表示要执行的分析函数,如SUM、AVG、ROW_NUMBER等;<column_list>
是分区和排序的列名;window_clause
用于指定窗口规范,如RANGE或ROWS等。
例如,要计算每个部门的平均工资与该部门内的所有员工的平均工资之间的差异,可以使用以下查询:
SELECT
department_id,
employee_id,
salary,
AVG(salary) OVER (PARTITION BY department_id) AS department_avg_salary,
AVG(salary) OVER () AS overall_avg_salary,
AVG(salary) OVER () - AVG(salary) OVER (PARTITION BY department_id) AS salary_difference
FROM employees;
在这个例子中,AVG(salary) OVER (PARTITION BY department_id)
计算每个部门的平均工资,AVG(salary) OVER ()
计算整个结果集的平均工资,然后计算每个部门的平均工资与整个结果集的平均工资之间的差异。