A table has a row for each date an employee is at work, and gives a multi-row result when a query is run on a specific employee. To obtain information on the latest date worked, I use the MAX function and group by date and other relevant columns to get the latest data for the employee. I also use the TOP (1) function to get only one row. This works well if I am querying one employee only. What I would like to do, is to query a group of employees via their EmpNo, and get the latest date worked for each employee. Remembering that each employee queried will yield several records that ends up as one record after the grouping and Top (1) function, how do I query several employees and get just one record with the latest data for each employee?
The query I used to get the single latest record for each employee looks like this:
SELECT TOP (1) EmpNo, Status, Title, MAX(DailyDate) AS Max
FROM EmpTable
WHERE EmpNo = 1234567
GROUP BY EmpNo, Status, Title, DailyDate
ORDER BY DailyDate DESC
I tried doing it this way but failed miserably. How else can I do the query to achieve this?
SELECT DISTINCT EmpTable.EmpNo, EmpTable.Status, EmpTable.Title, TEMP.Max
FROM EmpTable INNER JOIN
(SELECT TOP (1) EmpNo, Status, Title, MAX(DailyDate) AS Max
FROM EmpTable AS EmpTable_1
WHERE (EmpTable_1.EmpNo = EmpNo)
GROUP BY EmpNo, EmpNo, Status, Title, DailyDate
ORDER BY DailyDate DESC) AS TEMP ON EmpTable.EmpNo = TEMP.EmpNo
WHERE (EmpTable.EmpNo IN (240485, 491628, 587171, 329531, 261342, 241977, 213617, 154477, 142585, 279527, 409745, 290893, 191298, 197427, 156534, 147878))
Example of how the data is arranged in the table:
EmpNo Status Title DailyDate
1 A Programmer 4/22/2021
1 A Programmer 4/21/2021
1 A Programmer 4/20/2021
1 A Programmer 4/19/2021
1 A Programmer 4/16/2021
2 A Analyst 4/22/2021
2 A Analyst 4/21/2021
2 A Analyst 4/20/2021
2 A Analyst 4/19/2021
2 A Analyst 4/16/2021
3 A Secretary 3/31/2021
3 A Secretary 3/30/2021
3 A Secretary 3/29/2021
3 A Secretary 3/26/2021
3 A Secretary 3/25/2021
Result (showing most current dates per employee):
EmpNo Status Title DailyDate
1 A Programmer 4/22/2021
2 A Analyst 4/22/2021
3 A Secretary 3/31/2021
Based on the suggestion I got in the Stackoverflow answer below, I used the following SQL, but I got a listing of all 15 employees records shown above for EmpNos 1, 2 & 3, instead of the 3 records in the result set above.
SELECT EmpNo, Status, TITLE, DailyDate
FROM (
SELECT EmpNo, Status, TITLE, DailyDate,
ROW_NUMBER() OVER (PARTITION BY EmpNo, Status, TITLE, DailyDate ORDER BY DailyDate DESC) AS DateOrder
FROM SIF_Main
) TEMP
WHERE DateOrder = 1
AND EmpNo IN (1, 2, 3)
Your help will be greatly appreciated.