0

A column consists of dates only. I need to extract the latest 2 dates from the table. What is the best way to do it?

Example: Values in a table having date column as 01-01-2021, 01-02-2021, 01-03-2021 I would need 01-02-2021,01-03-2021 as my output.

Connor Low
  • 5,900
  • 3
  • 31
  • 52

2 Answers2

0

You can use rank() (or row_number() if there are no dupicliates):

select t.*
from t
qualify rank() over (order by datecol desc) <= 2;

Note: If you want distinct values, you could also use:

select distinct datecol
from t
order by datecol desc
limit 2;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can order the column and then select the top X elements that you require

Select Top 2 col_Date
from MyTable
Order by col_Date DESC

The returned result would be a column If you need to have a single string, there is a function that can help : STRING_SPLIT

Karlheim
  • 121
  • 5