Monday, March 19, 2012

Ms Sql Query

I am trying to write a query that will choose a row without duplicates. The table is used as a checking in/out log and I need to query the latest check in or out. There is a column that is in date-time format that records the time of the check in or out, so inside of my query, how can I grab all of the distinct rows, choosing the latest check in or out transaction for each user?

Quote:

Originally Posted by mbarnes2231

I am trying to write a query that will choose a row without duplicates. The table is used as a checking in/out log and I need to query the latest check in or out. There is a column that is in date-time format that records the time of the check in or out, so inside of my query, how can I grab all of the distinct rows, choosing the latest check in or out transaction for each user?

Please try this in SQL 2005

WITH [TEMPTABLENAME] AS
(SELECT ROW_NUMBER() OVER (PARTITION BY user ORDER BY loginout_datetime desc) AS ROWID, * FROM logtablename)
SELECT user,loginout_datetime FROM [TEMPTABLENAME] WHERE ROWID=1

No comments:

Post a Comment