我正在尝试获取员工及其国籍的列表:
select concat([Firstname],[Lastname]) as 'Full name',[C].[Label] as 'Nationality' FROM [Employee] [E]
left join [AF_AdminFile] [AFA] on E.AdminFileId=AFA.AdminFileId
left join [AF_Nationality] [AFN] on AFN.AdminFileId= AFA.AdminFileId
left join [Country] [C] on AFN.CountryId=C.ID
结果,我得到了以下内容:
在这种情况下,员工已更改了国籍,因此Employee
表中有一个名为UpdatedDate
的属性,该属性与NULL不同(一旦更改了国籍)
当我在查询中添加日期条件以获取max(UpdatedDate)
以获得“ DavidFELTEN”的最后一条记录时,我得到的结果与上图相同:
select concat([Firstname],[Lastname]),[C].[Label] as 'Nationality' FROM [Employee] [E]
left join [AF_AdminFile] [AFA] on E.AdminFileId=AFA.AdminFileId
left join [AF_Nationality] [AFN] on AFN.AdminFileId= AFA.AdminFileId
left join [Country] [C] on AFN.CountryId=C.ID
where [E].UpdatedDate = (select max([Emp].UpdatedDate) from [Employee] [Emp]
where [Emp].EmployeeId=[E].EmployeeId)
答案 0 :(得分:3)
使用ROW_NUMBER
:
WITH cte AS (
SELECT CONCAT([Firstname], [Lastname]) AS full_name,
[C].[Label] AS Nationality,
ROW_NUMBER() OVER (PARTITION BY E.EmployeeId ORDER BY UpdateDate DESC) rn
FROM [Employee] [E]
LEFT JOIN [AF_AdminFile] [AFA]
ON E.AdminFileId = AFA.AdminFileId
LEFT JOIN [AF_Nationality] [AFN]
ON AFN.AdminFileId = AFA.AdminFileId
LEFT JOIN [Country] [C]
ON AFN.CountryId = C.ID
)
SELECT
full_name,
Nationality
FROM cte
WHERE rn = 1;