where子句中的SQL Max(Date)

时间:2016-09-13 20:20:36

标签: sql max where

使用SQL Server

我正在使用以下2个表格,我希望回答以下问题:查找所有员工的最新工资率和更改日期。

表1:EmployeePayHistory

  1. BusinessEntityID
  2. RateChangeDate
  3. 表2:员工

    1. BusinessEntityID(员工ID)
    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
      

      我很难理解如何显示最新RateChangeDateBusinessEntityID。我认为Group By函数和MAX日期可以解决它。有什么建议吗?

1 个答案:

答案 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