我尝试使用LEAD为以下sql查询中的每一行获取最大日期差异,然后按降序排序。以下是查询及其结果。我希望能够做的还包括当前日期。目前,我无法包含最近记录的事件与今天的日期之间的差异。
因此,在我想要的结果中,提前日期将是今天的日期(在非有序的当前结果查询中它是空的)。目前的情况是,最后记录的事件是2016年12月5日,这意味着最后记录的事件与今天的事件之间的差异大约是63天。
使用SQL SERVER
查询:
Select
convert(varchar, CLL.Call_Log_Date, 101) as [CreatedDate],
convert(varchar, Lead(CLL.Call_Log_Date, 1)
Over (Order by CLL.Call_Log_Date DESC), 101) as [Lead],
DATEDIFF(dd, Lead(CLL.Call_Log_Date, 1)
Over (Order by CLL.Call_Log_Date DESC ), CLL.Call_Log_Date) as [DIFF]
From VMWareSM_Test.dbo.RV_CALL as CLL
Where CLL.IPK_Status_Ref = '1'
And CLL.Call_Priority_Ref IN (6,7)
Order by [DIFF] DESC;
结果
CreatedDate Lead DIFF
06/24/2015 05/12/2015 43
11/20/2015 10/09/2015 42
05/13/2016 04/08/2016 35
10/09/2015 09/14/2015 25
01/13/2015 12/23/2014 21
12/22/2014 12/03/2014 19
01/08/2016 12/21/2015 18
03/02/2015 02/12/2015 18
08/23/2015 08/07/2015 16
04/08/2016 03/25/2016 14
答案 0 :(得分:1)
使用Coalesce将NULL值替换为今天的日期。
Select
convert(varchar, CLL.Call_Log_Date, 101) as [CreatedDate],
convert(varchar, Coalesce(Lead(CLL.Call_Log_Date, 1)
Over (Order by CLL.Call_Log_Date DESC), GetDate()), 101) as [Lead],
DATEDIFF(dd, Coalesce(Lead(CLL.Call_Log_Date, 1)
Over (Order by CLL.Call_Log_Date DESC ), GetDate()), CLL.Call_Log_Date) as [DIFF]
From VMWareSM_Test.dbo.RV_CALL as CLL
Where CLL.IPK_Status_Ref = '1'
And CLL.Call_Priority_Ref IN (6,7)
Order by [DIFF] DESC;