使用SQL Server
我正在使用以下2个表格,我希望回答以下问题:查找所有员工的最新工资率和更改日期。
表1:EmployeePayHistory
表2:员工
我制作的SQL语句但不起作用:
SELECT DISTINCT
e.BusinessEntityID as [Employee], eph.rate
FROM
humanresources.employee AS e
JOIN
humanresources.employeepayhistory as eph ON e.BusinessEntityID = eph.BusinessEntityID
GROUP BY
e.BusinessEntityID, eph.Rate
HAVING
MAX(eph.ratechangedate)
我也尝试过:
SELECT
e.BusinessEntityID AS [Employee], eph.rate,
MAX(eph.RateChangeDate)
FROM
humanresources.employee AS e
JOIN
humanresources.employeepayhistory as eph ON e.BusinessEntityID = eph.BusinessEntityID
GROUP BY
E.BusinessEntityID, eph.Rate
我很难理解如何显示最新RateChangeDate
每BusinessEntityID
。我认为Group By
函数和MAX
日期可以解决它。有什么建议吗?
答案 0 :(得分:3)
根据您的数据库,可能有一个更简单的选项(例如使用row_number
)。但是,这是一个join
的通用方法:
select e.BusinessEntityID, e.RateChangeDate, e.Rate
from EmployeePayHistory e
join (select BusinessEntityID, max(RateChangeDate) RateChangeDate
from EmployeePayHistory
group by BusinessEntityID) e2 on e.BusinessEntityID = e2.BusinessEntityID
and e.RateChangeDate = e2.RateChangeDate
如果您的数据库支持window functions
,那么这应该有效:
select *
from (
select *,
row_number() over (partition by BusinessEntityID order by RateChangeDate desc) as rn
from EmployeePayHistory
) t
where rn = 1