我想找到每位员工的独特评论(按年份),仅显示最近的评论(按年份)
Employee List Employee Reviews
Number | Employee Name GUID | Number | Year
1234 John x5848 1234 2016
4526 Jim xd565 1234 2015
1123 Pam cr484 1123 2016
需要的结果:
Number | Name | GUID | Year
1234 John x5848 2016
1123 Pam cr484 2016
我无法弄清楚如何编写一个可以返回上述结果的SQL查询。任何人都有这样或类似的查询经验吗?
答案 0 :(得分:1)
您可以通过向其提供行号来对记录进行排名:
select
guid, number, year,
row_number() over (partition by number order by year desc) as rn
from employee_reviews;
这为每位员工(order by year desc
)第1行提供了最新记录(partition by number
)。因此:
select emp.number, emp.name, rev.guid, rev.year
from employee amp
join
(
select
guid, number, year,
row_number() over (partition by number order by year desc) as rn
from employee_reviews
) rev on rev.number = emp.number and rev.rn = 1;