With all due respect webadept, you may have rushed through this answer
a bit too quickly. Notice you are selecting fields in your query that
are neither calculated nor in the group by clause. As such, the query
you suggested is invalid.
In any case, a subquery is required and a single table query approach
will not suffice for what the questioner is asking. Even if you
modified your query to the following:
select employeeID, Name, Department, Address, max(TimeDateStamp)
from tablename
group by employeeID, Name, Department, Address
order by Name
.. we would not get only one address for each employee as required.
The following test script contains a working query to get the proper results:
create table Employees (
EmployeeID int,
Name varchar(50),
Department varchar(50),
Address varchar(50),
TimeDateStamp smalldatetime )
insert into Employees (EmployeeID, Name, Department, Address, TimeDateStamp)
values ('1','John Smith','ar','123 Nowhere','1/1/2003')
insert into Employees (EmployeeID, Name, Department, Address, TimeDateStamp)
values ('1','John Smith','ar','456 Anywhere','6/30/2004')
-- THIS QUERY WILL GET THE LATEST DEPARTMENT AND ADDRESS FOR EACH EMPLOYEE
select e.EmployeeID,
Name,
Department,
Address,
LastUpdate
from Employees e
join ( select EmployeeID,
max(TimeDateStamp) as LastUpdate
from Employees
group by
EmployeeID ) lu
on (e.EmployeeID = lu.EmployeeID and e.TimeDateStamp = lu.LastUpdate) |