问题
So I have an issue with SQlite. I have a table results.
I want to write a query now that gives me back not the latest, but the row after that. Let's take a look on an example:
ID,searchID,hit,time
1,1,3,1-1-2008
1,1,8,1-1-2009
1,1,4,1-1-2010
1,2,9,1-1-2011
1,2,10,1-1-2009
and I want to get back one time per searchID now (the pre-latest):
1,1,8,1-1-2009
1,2,10,1-1-2009
It is really easy to do it with the last time
SELECT searchID, hit, max(time)
FROM results
group BY searchID
But I need the pre-latest for some reasons.
PS: this one I found What is the simplest SQL Query to find the second largest value? but was not able to apply for my case.
回答1:
Using any other day/month than 1/1 will foul up the date string comparisons; you should use a date format like yyyy-mm-dd
instead.
Assuming that you have working date comparisons, you can either remove all the maximum rows with a compound query, then group over the rest:
SELECT searchID, hit, MAX(time)
FROM (SELECT searchID, hit, time
FROM results
EXCEPT
SELECT searchID, hit, MAX(time)
FROM results
GROUP BY searchID)
GROUP BY searchID
or you can check, before the grouping, that the time is not the largest time in the group:
SELECT searchID, hit, MAX(time)
FROM results
WHERE time < (SELECT MAX(time)
FROM results AS r2
WHERE r2.searchID = results.searchID)
GROUP BY searchID
来源:https://stackoverflow.com/questions/26662167/get-back-the-second-latest-date-per-id-instead-of-the-latest