Oracle分析函數——函數用法

 Oracle分析函數——函數用法php

  Oracle分析函數實際上操做對象是查詢出的數據集,也就是說不需二次查詢數據庫,實際上就是oracle實現了一些咱們自身須要編碼實現的統計功能,對於簡化開發工做量有很大的幫助,特別在開發第三方報表軟件時是很是有幫助的。Oracle8.1.6開始提供分析函數。數據庫

oracle分析函數的語法:oracle

function_name(arg1,arg2,...)ide

over函數

(<partition-clause> <order-by-clause ><windowing clause>)編碼

     說明:spa

1. partition-clause 數據記錄集分組.net

2. order-by-clause  數據記錄集排序orm

3. windowing clause 功能很是強大、比較複雜,定義分析函數在操做行的集合。有三種開窗方式: rangerowspecifying對象

 

--Partition by,按相應的值(manager_id)進行分組統計

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

  hire_date,

 salary,

 AVG(salary) OVER (PARTITION BY manager_id) avg_salary

FROM employees;

--等同於上面

SELECT

 a.manager_id,

 a.employee_name,

 a.hire_date,

 a.salary,

 b.avg_salary

FROM

(

 SELECT

   manager_id,

   first_name||' '||last_name employee_name,

   hire_date,

   salary

   FROM employees

) a,

(

 SELECT

   manager_id,

   AVG(salary) avg_salary

   FROM employees

  GROUP BY manager_id

) b

WHERE a.manager_id=b.manager_id

ORDER BY a.manager_id

 

--Order by按相應的值(hire_date)進行排序並累計統計

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

 hire_date,

 salary,

 AVG(salary) OVER (ORDER BY hire_date)

FROM employees;

--Partition by Order by首先按相應的值(manager_id,hire_date)排序,並按order by的值(hire_date)進行累計統計

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

 hire_date,

 salary,

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date)

FROM employees;

--Partition by Order by首先按相應的值(manager_id,hire_date)排序,並按order by的值(hire_date)進行累計統計

--該平均值由當前員工和與之具備相同經理的前一個和後兩個三者的平均數得來

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

 hire_date,

 salary,

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date ROWS BETWEEN 1 PRECEDING AND 2 FOLLOWING)

FROM employees;

 

--Partition by Order by首先按相應的值(manager_id,hire_date)排序,並按order by的值(hire_date)進行累計統計

--該平均值由當前員工和與之具備相同經理,而且僱用時間在該員工時間以前的50天之內和在該員工以後的150天以內員工的薪水的平均值

--range爲取值範圍,估計只有數字和日期可以進行取值了

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

 hire_date,

 salary,

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date RANGE BETWEEN 50 PRECEDING AND 150 FOLLOWING)

FROM employees;

--Partition by Order by首先按相應的值(manager_id,hire_date)排序,並按order by的值(hire_date)進行累計統計

--該平均值由當前員工和與之具備相同經理的平均值

--每行對應的數據窗口是從第一行到最後一行

SELECT

 manager_id,

 first_name||' '||last_name employee_name,

 hire_date,

 salary,

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date) avg_salary_part_order,

 AVG(salary) OVER (PARTITION BY manager_id ) avg_salary_order, 

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) avg_salary_unbound1, --等同於僅partition時候的值

 AVG(salary) OVER (PARTITION BY manager_id ORDER BY hire_date ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) avg_salary_unbound2--等同於上面

FROM employees;

 

相關文章
相關標籤/搜索