Reputation: 6668
I would like to know how if it is possible to select the two most recent dates from a column in a table. Please see the simple example below. I know to get the max date I can use the max function. I'm also aware that I could then do another max statement with a where condition that states it must be less than the first date returned from my first max query. I was wondering though if there was a way of doing this in one query?
Name DateAdded
ABC 2014-04-20
ABC 2014-04-20
ABC 2014-03-01
ABC 2014-03-01
ABC 2014-02-25
ABC 2014-05-22
ABC 2014-04-01
The two dates that should be returned are the two most recent, i.e. 2014-05-22 & 2014-04-20.
EDIT
Sorry I should have mentioned yes I want two distnict dates. The table is large and the dates are not sorted. I think sorting the table could be quite slow.
Upvotes: 0
Views: 1791
Reputation: 24
Try This :
select distinct top(2) format(Dateadded ,'yyyy-MM-dd') as Dateadded from TableName order by Dateadded DESC
Upvotes: 0
Reputation: 44336
SELECT distinct top 2 Dateadded
FROM table
ORDER BY Dateadded desc
Upvotes: 1