2

I have the following query:

SELECT
a.name, a.address, n.date, n.note
FROM a
LEFT JOIN n ON a.id = n.id

The a.id has a one to many relationship with n.id, so that many notes can be assocaited with one name.

How do I return just the latest note for each name instead of all the notes?

I'm using SQL Server 2008.

Thanks.

1 Answer 1

5

Here's one way using ROW_NUMBER()

SELECT t.name, t.address, t.date, t.note
FROM (
    SELECT
        a.name, a.address, n.date, n.note,
        ROW_NUMBER() OVER (PARTITION BY a.name ORDER BY n.date DESC) rn
    FROM a
    LEFT JOIN n ON a.id = n.id
) t
WHERE t.rn = 1

alternative you can use a correlated subquery too get the max date, something like this

SELECT
    a.name, a.address, n.date, n.note
FROM a
LEFT JOIN n ON a.id = n.id
WHERE n.date = (SELECT MAX(nn.date) 
                FROM n AS nn 
                WHERE a.id = nn.id)
Sign up to request clarification or add additional context in comments.

10 Comments

Good answer, but possibly overkill?
@SelectDistinct do you have a simpler way to accomplish the desired result? If so, why not post an answer, or elaborate on why you think this is overkill.
Hi T I, Thanks for your response. The script is actually a simplified version of a larger, more complex query involving many tables and joins. Is there an alternative to having the entire query in a sub query of the From clause as this means any change to a field, join etc. needs to be done twice? Thanks.
Try adding OR n.date IS NULL to the main query's WHERE clause
@SelectDistinct while that may look simpler I'd compare the plans. SQL might be very smart about optimizing them the same way, but it might not.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.