Let's say I have a table:
Name, status, timestamp
And I want to select the rows that match status='active' but only those that have the most recent timestamp for each of them. So if there were rows like this:
Bob, active, 5/10/2010
Bob, active, 6/12/2010
Ann, inactive, 6/12/2000
Ann, active, 9/3/2009
Ann, active, 9/25/2010
I'd want it to return:
Bob, active, 6/12/2010
Ann, active, 9/25/2010
How can I do this? I'm using SQLite, if it matters.
Thank you.
take a look at http://www.w3schools.com/sql/sql_groupby.asp
Here's how I solve this type of problem. You want one row for each name such that no other row exists with the same name and a greater timestamp:
But this can still return multiple rows for each name, because you could have more than one row for a given name with the same max timestamp. So use the primary key as a tie-breaker:
I'm assuming
id
is a primary key for this example, but any other unique column that increases in value chronologically would work.Bill, I believe I have it working now (seems to pick the right rows on different test data). I used your query and added the condition t1.active_status!='active', since that will take care of anything inactive. The whole query looks like:
Thank you very much for the help. Obviously, I'm new to more than basic SQL queries. This helps teach me, thanks!