在SQL Server中领先和落后
我正在尝试确定保存票证后是否应用了模板。 代码确实运行,但它不从操作列捕获字符串"模板已应用"。
这是我获取数据的表格:
以下是我得到的结果:
我的代码:
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
解决方案
您似乎需要将部分order by
移动到partition by
在lead
和lag
语句中,将over
子句更改为
OVER (PARTITION BY SYS_CREATED_BY ORDER BY SYS_CREATED_ON DESC)
这将确定您希望按人员查看它的位置。
如果您不介意,可以将其完全删除
OVER ( ORDER BY SYS_CREATED_ON)
相关文章