5

我在 SQL Server 中有一个表,其中包含由 BusinessDataDate 组织的数据。BusinessDataDate 仅是日期(无时间组件),仅在工作日填充。例如不是周末或公共假期。

因为没有具体的顺序,所以我想找到date before the current max date

此查询有效,我可以将值设置为局部变量 - 但感觉必须有更清洁的方法?

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

每个日期在表格中都有多行 - 确切的数字是不可预测的。

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 回答