我的桌子每位员工每年有一条记录。如何为每位员工选择一条记录,以获得该员工的最新一年?
列为employee_ref, firstname, lastname, employment_year
。
每个employee_ref
都会有多条记录,每条记录都有employment_year
我想为每个employee_ref
选择一条记录,其中employment_year
具有该employee_ref
的最高值,并显示此记录中的firstname
和lastname
虽然我知道SQL,但我的技能并不适合这个。
答案 0 :(得分:2)
您可以使用子选择执行此操作:
SELECT employee_ref, firstname, lastname
FROM table
WHERE employment_year = (
SELECT MAX(employment_year)
FROM table b
WHERE b.employee_ref = table.employee_ref)
答案 1 :(得分:0)
这样的事情应该有效。
select firstname, lastname, maxyear
from table join (
select employee_ref, max(employment_year) maxyear
from table
group by employee_ref) temp on table.employee_ref = temp.employee_ref
and employment_year = maxyear
答案 2 :(得分:0)
假设employment_year是一个整数,你可以做类似的事情:
SELECT TOP 1 * from (select * from employee where employment_ref=x order by employment_year)
有关详细信息,请参阅here。
答案 3 :(得分:0)
这应该有效:
with EmployeesMostRecentYear as
(
SELECT [Employee_ref]
,[firstname]
,[lastname]
,[employment_year]
,ROW_NUMBER() over (partition by [Employee_ref],[firstname],[lastname] order by [employment_year] desc) as YearIndex
FROM [TestDb].[dbo].[Employees] E
)
select * from EmployeesMostRecentYear
where YearIndex = 1