Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 find last 2 records

Author  Topic 

callumny
Starting Member

1 Post

Posted - 2008-09-26 : 13:26:32
Can someone help me? I am trying to write a query that will find the TWO most recent records for each person. I can do it in 2 different queries, but I don't know how I would combine them, or if I can.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-09-26 : 13:29:48
If you use SQL Server 2005 or later, try the ROW_NUMBER() function.



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-09-26 : 13:34:51
[code]SELECT *
FROM
(SELECT ROW_NUMBER() OVER(PARTITION BY personname ORDER BY PK DESC) AS Seq,*
FROM YourTable)t
WHERE t.Seq<=2[/code]

pk is primary key of your table.
Go to Top of Page
   

- Advertisement -