Get back the second latest date per ID instead of the latest

隐身守侯 提交于 2019-12-08 03:52:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!