5

I have a table in SQL Server that holds data organised by BusinessDataDate. BusinessDataDate is a Date only (no time component) and is only populated on Business days. e.g. not Weekends or public holidays.

Because there is no specific order to this, I want to find the date before the current max date

This query works, and I can set the values into local variables - but it feels like there must be a cleaner way?

SELECT MAX(BusinessDataDate) FROM myTable 
  WHERE BusinessDataDate < (SELECT MAX(BusinessDataDate) FROM myTable)

Each date will have multiple rows in the table - the exact number is not predictable.

4

2 に答える 2

3
SELECT TOP (1)
    BusinessDataDate
FROM
    (
    SELECT
        BusinessDataDate,
        DENSE_RANK() OVER (ORDER BY BusinessDataDate DESC) as rn
    FROM
        myTable
    ) x
WHERE
    x.rn = 2
ORDER BY
    x.BusinessDataDate;
于 2013-04-22T11:05:24.720 に答える
2

元のクエリに似ていますが、上位 1 を使用するのはどうですか?

SELECT Top 1 BusinessDataDate 
FROM myTable 
WHERE BusinessDataDate < (SELECT MAX(BusinessDataDate) FROM myTable)
ORDER BY BusinessDataDate DESC
于 2013-04-22T11:10:21.220 に答える