TSQL - 获取上次成功日期

时间:2017-02-14 15:40:45

标签: sql-server

我对以下逻辑感到震惊。每当状态失败时,我需要max(EndTime)以前成功。例如,在以下数据中,对于Batch = 3987lastrefreshdate应为23-01-2017,而不是13-02-2017

以下是数据和查询的摘要。

Batch   TableName   IsFullLoad  Status  EndTime     LastRefreshDate
5524    SA                 1    Loaded  13-02-2017  13-02-2017
4746    SA                 1    Loaded  06-02-2017  06-02-2017
4174    SA                 1    Loaded  31-01-2017  31-01-2017
3987    SA                 1    Failed  30-01-2017  13-02-2017
3372    SA                 1    Loaded  23-01-2017  23-01-2017
2651    SA                 1    Loaded  16-01-2017  16-01-2017
1987    SA                 1    Loaded  09-01-2017  09-01-2017
1379    SA                 1    Loaded  02-01-2017  02-01-2017
835     SA                 1    Loaded  26-12-2016  26-12-2016
189     SA                 1    Loaded  19-12-2016  19-12-2016
52      SA                 1    Loaded  17-12-2016  17-12-2016

SQL:

SELECT TOP 40*
FROM (
SELECT
bi.Id,
bi.TableName,
bi.IsFullLoad,
bi.JobId,
[Status],
bi.CompletTime,
CASE 
WHEN bi.IsFullLoad = 1 AND bi.[Status] = 'Failed' 
THEN
(
SELECT MAX(CompletTime) FROM  Audit.T1 bb
  WHERE [Status]= 'Loaded' AND bb.IsFullLoad = 1  AND bb.TableName = bi.TableName 
  GROUP BY bb.TableName
  )
 ELSE 
 bi.CompletTime 
 END AS Validto
FROM Audit.T1 bi
WHERE TableName = 'Salesforce_Account' AND bi.IsFullLoad = 1
) x 
ORDER BY x.CompletTime desc

非常感谢任何帮助。 在此先感谢。

1 个答案:

答案 0 :(得分:1)

您的内部查询是从满足条件的表格中选择最后一个completTime,但在您引用当前记录CompletTime的条件中没有位置。

从内部更改内部查询:

SELECT MAX(CompletTime) FROM  Audit.T1 bb
WHERE [Status]= 'Loaded' AND bb.IsFullLoad = 1  AND bb.TableName = bi.TableName 
GROUP BY bb.TableName

对此:

SELECT TOP 1 CompletTime 
FROM  Audit.T1 bb
WHERE [Status]= 'Loaded' 
AND bb.IsFullLoad = 1  
AND bb.TableName = bi.TableName 
AND CompletTime < b1.CompletTime
ORDER BY CompletTime DESC

当然,您仍然可以使用MAX - 但添加相关条件。

Group by