How to retrieve the second most recent date in a table?

  • Is there anyway to read a table with Dates and return the most recent date and the second most recent date? For example, I have a Dates Table which only contains a date field. I want to always access the most recent date and the previous date (the date before the most recent date).  I could not use the DATEADD(day, -1, @BusinessDate) Function because the Dates Table only stores Business Dates (no weekends or holidays). So, on a Monday the Previous Business Date would be that previous Friday.

    To get the most recent date, I use:

    SELECT @BusinessDate = Max(Date) FROM DatesTable

    Next, I would like to get the second most recent date.

    SELECT @PrevBusinessDate = ???????

    The below statement did not help me any.

    SELECT TOP 2 *

    FROM FISQL.dbo.Dates

    ORDER BY Date Desc

    Thanks in advance.

  • select max( dt) from mytable

    where dt < (select max( dt) from mytable))

  • SELECT     TOP 2 ejoindate

    FROM         etest

    GROUP BY ejoindate

    ORDER BY ejoindate DESC

    (Above query will display the two dates as two rows)

     

    SELECT     MAX(ejoindate) AS m1,

                              (SELECT     MAX(ejoindate)

                                FROM          etest

                                WHERE      ejoindate <

                                                           (SELECT     MAX(ejoindate)

                                                             FROM          etest)) AS m2

    FROM         etest

     

    (above query will show m1 as max date and m2 second max date in single row)

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply