sqlsql-serveradventureworks

Finding the Latest Date for the Pay Rate


There have been similar questions raised, but I wanted some clarity nevertheless. I have been using the AdventureWorks2017 package on SQL and I am meant to get 290 rows as my answer. However using the code below I have been trying to achieve that, but with minimal success under my belt.

SELECT a.[NationalIDNumber], a.[Gender], b.[Rate], b.RateChangeDate, b.[PayFrequency], a.[BusinessEntityID], b.[ModifiedDate]
FROM [AdventureWorks2017].[HumanResources].[Employee] a
INNER JOIN [AdventureWorks2017].[HumanResources].[EmployeePayHistory] b ON a.[BusinessEntityID] = b.[BusinessEntityID]
AND b.RateChangeDate = MAX(b.RateChangeDate)
ORDER BY BusinessEntityID

My goal is essentially this: I want to find the employees' latest pay rate. I have tried some different types of queries to get my desired answer, but often I get either 277 or 316 rows (when I should get 290). I have tried finding the max of the RateChangeDate and max of the Rate, but with no success. The main line I am trying to modify is the one starting with 'AND'. Any help would be great!

Also here is a schema for AdventureWorks2008 (though it's not 2017), in case some clarity is needed.

AdventureWorks 2008 Schema (not 2017 - the one I am using) enter image description here


Solution

  • You can partition the EmployeePayHistory table, order by the date descending and then select the most recent as part of your inner join.

        SELECT a.[NationalIDNumber], a.[Gender], b.[Rate], b.[RateChangeDate], b.[PayFrequency], a.[BusinessEntityID], b.[ModifiedDate]
        FROM [AdventureWorks2017].[HumanResources].[Employee] a
        INNER JOIN (Select ROW_NUMBER() OVER (PARTITION BY eph.[BusinessEntityID] ORDER BY eph.[RateChangeDate] DESC) AS 'PayOrderDesc'
                            , eph.*
                    FROM [AdventureWorks2017].[HumanResources].[EmployeePayHistory] eph) b 
            ON a.[BusinessEntityID] = b.[BusinessEntityID]
            and b.PayOrderDesc = 1
        ORDER BY BusinessEntityID