简体   繁体   中英

MS Access Select Top 2 most recent dates relative to ID

I have a table with a large list of IDs for people

And for each ID there are many dates

example

ID
1 21/09/2016
1 24/09/2016 
3 09/01/2017
3 04/01/2016
3 31/12/2016
13 1/10/2016
13 1/11/2016
4 12/12/2016

I am needing to write a Microsoft Access Query that returns a table which select the TOP 2 most recent dates for each id. So for ID 3 (in table above) it would return 09/01/2017 and 04/01/2017 as these are the two most recent dates for that id.

Any idea?

Try this:

Select A.ID, A.Date 
from  (
        Select Id, Date , 
        Rank() OVER (Partition by Id order by Date Desc) as daterank 
        from tablename
      ) A
Where A.daterank < 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM