第十八单元:SQL进阶功能

分析函数提供一系列比较高级的SQL功能。分析函数是建立再数据窗口(over再一定范围进行数据分析),再一定的数据范围进行排序,汇总等.

查询当前员工所在部门的平均工资,最高工资和最低工资,即可通过分析函数来实现。

select e.last_name,e.salary,d.department_name,
        avg(e.salary) over(partition by d.department_name) department_avg_salary,
        max(e.salary) over(partition by d.department_name) department_avg_salary,
        min(e.salary) over(partition by d.department_name) department_avg_salary
from employees e,departments d
where 1 = 1
    and e.department_id = d.department_id;

将一个部门内的员工的工资从高到低进行排序,注意三种排序结果是不一样的。

select d.department_name,e.last_name,e.salary,
        rank() over(partition by d.department_name order by e.salary desc) dept_salary_rank1,
        dense_rank() over(partition by d.department_name order by e.salary) dept_salary_rank2,
        row_number() over(partition by d.department_name order by e.salary) dept_salary_rank3
from employees e,departments d
where 1 = 1
    and e.department_id = d.department_id; 

你可能感兴趣的:(第十八单元:SQL进阶功能)