Oracle分析函数三——SUM,AVG,MIN,MAX,COUNT

2022-03-11 16:54:23 浏览数 (1)

SUM

功能描述:该函数计算组中表达式的累积和。

SAMPLE:下例计算同一经理下员工的薪水累积值

MIN

功能描述:在一个组中的数据窗口中查找表达式的最小值。

SAMPLE:下面例子中dept_min返回当前行所在部门的最小薪水值

MAX

功能描述:在一个组中的数据窗口中查找表达式的最大值。

SAMPLE:下面例子中dept_max返回当前行所在部门的最大薪水值

AVG

功能描述:用于计算一个组和数据窗口内表达式的平均值。

SAMPLE:下面的例子中列c_mavg计算员工表中每个员工的平均薪水报告

代码语言:javascript复制
SELECT 
  department_id, 
  first_name||' '||last_name employee_name, 
  hire_date,  
  salary,
  MIN(salary) OVER (PARTITION BY department_id order by hire_date) AS dept_min,
  MAX(salary) OVER (PARTITION BY department_id order by hire_date) AS dept_max,  
  AVG(salary) OVER (PARTITION BY department_id order by hire_date) AS dept_avg,    
  SUM(salary) OVER (PARTITION BY department_id order by hire_date) AS dept_sum/*,    
  COUNT(*) OVER (ORDER BY salary) AS count_by_salary,  
  COUNT(*) OVER (ORDER BY salary RANGE BETWEEN 50 PRECEDING AND 150 FOLLOWING) AS count_by_salary_range*/
FROM employees 

COUNT

功能描述:对一组内发生的事情进行累积计数,如果指定*或一些非空常数,count将对所有行计数,如果指定一个表达式,count返回表达式非空赋值的计数,当有相同值出现时,这些相等的值都会被纳入被计算的值;可以使用DISTINCT来记录去掉一组中完全相同的数据后出现的行数。

SAMPLE:下面例子中计算每个员工在按薪水排序中当前行附近薪水在[n-50,n 150]之间的行数,n表示当前行的薪水

例如,Philtanker的薪水2200,排在他之前的行中薪水大于等于2200-50的有1行,排在他之后的行中薪水小于等于2200+150的行没有,所以count计数值cnt3为2(包括自己当前行);cnt2值相当于小于等于当前行的SALARY值的所有行数

代码语言:javascript复制
SELECT 
  department_id, 
  first_name||' '||last_name employee_name, 
  salary,
  COUNT(*) OVER (ORDER BY salary) AS count_by_salary,  
  COUNT(*) OVER (ORDER BY salary RANGE BETWEEN 50 PRECEDING AND 150 FOLLOWING) AS count_by_salary_range
FROM employees 
WHERE department_id in (10,20,30);

0 人点赞