Retrieving the most recent records within a query

后端 未结 3 2036
广开言路
广开言路 2020-12-15 08:15

I have the following tables:

tblPerson:

PersonID | Name
---------------------
   1     | John Smith
   2     | Jane Doe
   3     | David Hoshi
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 08:46

    As @Mark Byers mentions, this problem comes up frequently on Stack Overflow.

    Here's the solution I most frequently recommend, given your tables:

    SELECT p.*, l1.*
    FROM tblPerson p
    JOIN tblLocation l1 ON p.PersonID = l1.PersonID
    LEFT OUTER JOIN tblLocation l2 ON p.PersonID = l2.PersonID AND 
      (l1.timestamp < l2.timestamp OR l1.timestamp = l2.timestamp AND l1.LocationId < l2.LocationId)
    WHERE l2.LocationID IS NULL;
    

    To see other examples, follow the tag greatest-n-per-group, which I added to your question.

提交回复
热议问题