Link to home
Start Free TrialLog in
Avatar of tommym121
tommym121Flag for Canada

asked on

SQL - Get the latest records

I have a table with columns

TimeStamp
FirstName
LastName
EmployeeID (Primary Key)
LastInsuranceClaimAmount

I like to create a query to generate a table of the latest claim for each employee since Jan 1, 2013.  In the table there can be more than one records related to a EmployeeID. Records before Jan 1, 2013 will not be take into consideration.

The result should have the same column as the above table.

Can anyone give me an idea how to do that? Thanks.
Avatar of chaau
chaau
Flag of Australia image

If I understood you correctly, this is what you need to do:

;WITH cte AS
(
Select EmployeeID,
[TimeStamp],
ROW_NUMBER() OVER(PARTITION BY EmployeeID ORDER BY [TimeStamp] DESC) rn
FROM Table1
)
Select t.[TimeStamp],
t.FirstName,
t.LastName,
t.EmployeeID,
t.LastInsuranceClaimAmount FROM Table1 t INNER JOIN CTE c ON c.EmployeeID=t.EmployeeID AND c.[TimeStamp] = t.[TimeStamp] AND c.rn=1
WHERE t.[TimeStamp] >= '20130101'

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of chaau
chaau
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tommym121

ASKER

My timestamp is generated using the GetDate()
ok then my comments don't apply,
but you probably should not use the word 'timestamp' as a fieldname :)
That's why I have exposed it in brackets in my answer
:) agreed, that certainly is needed.

But it's sort of worse than just using a reserved word because "timestamp" is currently so misleading in SQL Server Plus, at sometime in the future MS will adopt the standard meaning I believe - which will be a small nightmare in itself. Better IMHO to avoid using that term as a field name whenever possible.

time_stamp might be an alternative?
PortierPaul, thanks to straighten me on terms.
Thank you