SQL Server中的LEAD和LAG

时间:2018-07-04 00:58:02

标签: sql sql-server window-functions

我试图确定保存票证后是否已应用模板。 该代码可以运行,但不会捕获 ACTION 列中的“模板已应用”字符串。

这是我要获取数据的表:

enter image description here

这是我得到的结果:

enter image description here

我的代码:

SELECT *
FROM
    (SELECT              
         [ACTION], 
         CASE
            WHEN ACTION = 'Save' AND LAG(ACTION) OVER (ORDER BY SYS_CREATED_BY, SYS_CREATED_ON) LIKE 'Template Applied%' AND LAG(SYS_CREATED_BY) OVER (ORDER BY SYS_CREATED_BY, SYS_CREATED_ON) = SYS_CREATED_BY 
               THEN 1 
               ELSE 0 
         END AS RELEVANT_SAVE, 
         [TICKET_NUMBER], 
         [USER_ID], 
         [SYS_CREATED_BY], [SYS_CREATED_ON], 
         DATEPART(YEAR, [SYS_CREATED_ON]) AS YEAR, 
         DATEPART(MONTH, [SYS_CREATED_ON]) AS month
     FROM            
         TICKETSDB
     WHERE        
         (ACTION = 'Save' OR ACTION LIKE 'Template Applied%')) AS T

1 个答案:

答案 0 :(得分:1)

似乎您需要将order by的一部分移至partition by

leadlag语句中,将over子句更改为

OVER (PARTITION BY SYS_CREATED_BY ORDER BY SYS_CREATED_ON DESC) 

这将固定您要按人查看的位置。

或者如果您不在意将其完全删除

 OVER ( ORDER BY SYS_CREATED_ON)