我在SQL Server中有一个表,用于保存由BusinessDataDate组织的数据。 BusinessDataDate仅为日期(无时间组件),仅在工作日填充。例如不是周末或公众假期。
由于没有特定的订单,我想找到date before the current max date
此查询有效,我可以将值设置为局部变量 - 但感觉必须有更清洁的方式?
SELECT MAX(BusinessDataDate) FROM myTable
WHERE BusinessDataDate < (SELECT MAX(BusinessDataDate) FROM myTable)
每个日期在表格中都有多行 - 确切的数字是不可预测的。
答案 0 :(得分: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;
答案 1 :(得分:2)
与您的原始查询类似,但如何使用top 1?
SELECT Top 1 BusinessDataDate
FROM myTable
WHERE BusinessDataDate < (SELECT MAX(BusinessDataDate) FROM myTable)
ORDER BY BusinessDataDate DESC