select dept_no,emp_no,salary from ( select a.dept_no,a.emp_no,b.salary,dense_rank() over(partition by dept_no order by salary desc) dnrk from dept_emp a left join salaries b on a.emp_no = b.emp_no ) c where dnrk = 1
用到了窗口函数,就说一下窗口函数的几个知识点:
- 首先就是窗口函数在SQL中的执行顺序:from > where > group by > having > select > window子句 > order by > limit
- group by 与 partition by的一个区别
group by会影响数据的行数,而partition by不会,且partition by 必须在over()中使用
比如成绩表如下
name score
A 100
B 80
A 20
现在求每位同学的获得的总分
使用select name,sum(score) total_score from table group by name,结果如下
name score
A 120
B 80
使用select name , sum(score) over(partition by name) total_score from table group by name,结果如下
name score
A 120
B 80
A 120