-1
ID   | DATE       | OTHER | OTHER 
----------------------------------
ID45 | 8/22/2020  |       |
ID45 | 9/12/2020  |       |
ID45 | 12/13/2020 |       |
ID45 | 7/14/2020  |       |
ID56 | 3/15/2020  |       |
ID56 | 2/19/2020  |       |
ID56 | 9/24/2020  |       |
ID56 | 5/18/2020  |       |
ID72 | 7/20/2020  |       |

I would like to see all the data (all columns) related to the last 3 dates of an ID The result would be in this case:

ID   | DATE       | OTHER | OTHER 
----------------------------------
ID45 | 12/13/2020 |       |
ID45 | 9/12/2020  |       |
ID45 | 8/22/2020  |       |
ID56 | 9/24/2020  |       |
ID56 | 3/15/2020  |       |
ID56 | 2/19/2020  |       |

Could you please help me?

Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60

3 Answers3

0

You can use window functions:

select t.*
from (select t.*,
             row_number() over (partition by id order by date desc) as seqnum
      from t
     ) t
where seqnum <= 3;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0
SELECT * FROM (
    [ID],[Date]
    ROW_NUMBER() OVER (PARTITION BY [ID] ORDER BY [Date] DESC) AS rn
FROM YourTable) AS A
WHERE A.rn<=3
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
0

If in case you don't want to use windowed function, simpler solution is:

SELECT *
    FROM TABLE
        WHERE DATE IN (SELECT TOP 3 DATE FROM TABLE ORDER BY DATE DESC)
    ORDER BY DATE DESC