我有一张每天大约100,000行的表,每行包含添加的日期。但是,行仅在工作日添加,因此没有周末或银行假日。
我正在尝试找到一种有效的方法来查找Max(BusinessDate)
以及下一个最高max(BusinessDate)
。但是,当我尝试以下操作时,需要20分钟才能运行(总共+ 50Mn行)。
SELECT
MAX(t1.BusinessDataDate) AS BusinessDataDate
, MAX(t2.BusinessDataDate) AS PreviousDataDate
FROM
cb_account t1
, cb_account t2
WHERE
t2.BusinessDataDate < t1.BusinessDataDate
只需选择Max(BusinessDataDate)
即时。
SELECT TOP 2
'cb_account' AS TableName
, BusinessDataDate
FROM cb_account
GROUP BY BusinessDataDate
ORDER BY BusinessDataDate DESC
会给我两个日期,但我真的需要它们一行。
答案 0 :(得分:2)
SELECT MAX(dates.BusinessDataDate) AS BusinessDataDate,
MIN(dates.BusinessDataDate) AS PreviousDataDate
FROM
(SELECT TOP 2
'cb_account' AS TableName
, BusinessDataDate
FROM cb_account
GROUP BY BusinessDataDate
ORDER BY BusinessDataDate DESC) dates
答案 1 :(得分:1)
如果我说对了,试试这个:
WITH T as
(
SELECT MAX(BusinessDataDate) as MaxD
FROM cb_account
)
SELECT MaxD, (SELECT MAX(BusinessDataDate)
FROM cb_account
WHERE BusinessDataDate<T.MaxD)
FROM T
答案 2 :(得分:0)
您使用的SQL版本是什么?如果您使用的是SQL 2012,则可以使用LEAD()或LAG()函数