I have following fields and data in DB:
FirstName LastName Date
John Davis 10-10-2011
Joe Gray 20-09-2011
Ann Davis 03-04-2010
Ann Bovis 01-04-2010
How can I select from DB 3 items with latest date and unique last name with all other fields included in result. That is mean if there are more than one item with LastName Davis in result should be only one with latest date. Don't even know how to do it on pure SQL - and Django looks impossible at all.
EDIT1. SQL QUERY.
I wrote query on pure SQL:
SELECT TOP 3 *
FROM peopleTable as a1
WHERE (select count(*)FROM peopleTable as a2 where a2.LastName=a1.LastName and a2.Date > a1.Date)<=0
ORDER by Date desc
I guess it would be better if I use this query in django just as pure SQL.
You can do this:
or
but you can't do both. If you want to get the most recent date for last name Davis, which other fields should be retrieved, firstname=John or firstname=Ann?
I am guessing that you want the result to look like this:
Where the Ann Davis row is gone because she isn't the most recent Davis in the table. Correct?
In which case your raw SQL looks something like:
Which you can write up in Django using the Item.objects.raw() option. You can also use
extra(where=…)