SQL query to get the last selected value per person

  • Hi,

    I need some help with a SQL query. I've been trying to find a way to get the desired information but so far nothing seems to work right. I have a table which looks like this:personId int, selectedValue int, logDate datetime

    For each person there can be multiple records in the table. What I'd like to do is get the last selected value for each person in the table. I am able to get the last date a person selected something with this query:

    SELECT personId, MAX(logDate) FROM MySelectedValues GROUP BY personId

    Unfortunately I've been unable to come up with a query that will also retrieve the selected value. Any help would be much appreciated!

  • Try with this:

    SELECT A.personId, A.LogDate, A.selectedValue

    FROM MySelectedValues AS A

    INNER JOIN (

    SELECT personId, MAX(logDate) AS LogDate

    FROM MySelectedValues

    GROUP BY personId

    ) AS B

    ON A.personId = B.personId

    AND A.LogDate = B.LogDate

    Regards

    Gianluca

    -- Gianluca Sartori

  • Thanks, that works really well. You've been a great help!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply