-1

I need to select the latest record per memberid by DATETIME.

SAY my table is like this:

MemberID    CreatedDate
188         2013-01-31 08:10:15.990
188         2013-01-31 08:10:15.970
188         2013-01-24 19:36:01.840
244         2013-01-24 19:36:01.840
244         2013-01-31 08:10:15.970
244         2013-01-31 08:10:15.980

OUT:

188 2013-01-31 08:10:15.990
244 2013-01-31 08:10:15.980

SQL QUERY to select the latest based on date-Time-milliseconds.

Thank in advance for the help.

TMAN-MAN
  • 141
  • 1
  • 2
  • 13

3 Answers3

3

I think this is what you are looking for, you need to group the memberID and Find the max CreatedDate

Select memberId, max(CreatedDate) from members
Group By memberId
Lawrence Thurman
  • 657
  • 8
  • 15
2

The simplest is using a ranking function like ROW_NUMBER:

WITH CTE AS
(
   SELECT MemberID, CreatedDate, 
          RN = ROW_NUMBER() OVER (PARTITION BY MemberID 
                                  ORDER BY CreatedDate DESC)
   FROM dbo.TableName  
)
SELECT MemberID, CreatedDate FROM CTE WHERE RN = 1

This just returns one record per MemberID (the one with the latest CreatedDate). If you have multiple latest records an arbitrary is taken. If you want to take all in this case you have to replace ROW_NUMBER with DENSE_RANK.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

Is this you are looking for.

 select memberid,max(createddate)  createddate from Table
    group by memberid
Kishore
  • 846
  • 6
  • 9