w3resource

AdventureWorks Database: Fetch hiredate of last employee in a department for a salary

SQL Query - AdventureWorks: Exercise-106 with Solution

106. From the following tables write a query in SQL to return the hire date of the last employee in each department for the given salary (Rate). Return department, lastname, rate, hiredate, and the last value of hiredate.

Sample table: HumanResources.vEmployeeDepartmentHistory


Click to view Full table

Sample table: HumanResources.EmployeePayHistory


Click to view Full table

Sample table: HumanResources.Employee


Click to view Full table

Sample Solution:

SELECT Department
    , LastName
    , Rate
    , HireDate
    , LAST_VALUE(HireDate) OVER (
        PARTITION BY Department ORDER BY Rate
        ) AS LastValue
FROM HumanResources.vEmployeeDepartmentHistory AS edh
INNER JOIN HumanResources.EmployeePayHistory AS eph
    ON eph.BusinessEntityID = edh.BusinessEntityID
INNER JOIN HumanResources.Employee AS e
    ON e.BusinessEntityID = edh.BusinessEntityID
WHERE Department IN ('Information Services', 'Document Control');

Sample Output:

department          |lastname     |rate   |hiredate  |lastvalue |
--------------------+-------------+-------+----------+----------+
Document Control    |Chai         |  10.25|2009-01-22|2009-02-09|
Document Control    |Berge        |  10.25|2009-02-09|2009-02-09|
Document Control    |Kharatishvili|16.8269|2008-12-16|2009-03-06|
Document Control    |Norred       |16.8269|2009-03-06|2009-03-06|
Document Control    |Arifin       |17.7885|2009-01-04|2009-01-04|
Information Services|Bueno        |27.4038|2008-12-23|2009-01-11|
Information Services|Berg         |27.4038|2009-02-16|2009-01-11|
Information Services|Meyyappan    |27.4038|2009-02-03|2009-01-11|
Information Services|Bacon        |27.4038|2009-01-11|2009-01-11|
Information Services|Sharma       |32.4519|2008-12-04|2009-02-23|
...

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Return the difference in sales quotas for a specific employee over previous years.
Next: Find the sales quota difference between the current and the first and last quarter.


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.