SQL-LEAD函数

问题描述

我尝试使用以下代码:

 SELECT SkillTargetID,DateTime,lead(EventName,1) over (partition by EventName order by DateTime) as next_eventname,lead(ReasonCode,1) over (partition by ReasonCode order by DateTime) as next_ReasonCode
 FROM ucce1_awdb.dbo.Agent_State_Trace ast
 WHERE 
 EventName = 3 and
 ReasonCode= 0 and
 next_eventname = 0 and
 next_ReasonCode = 114

但是由于next_eventnamenext_ReasonCode,我无法执行该查询。有人可以建议我该如何处理吗?

解决方法

您需要一个子查询:

SELECT SkillTargetID,DateTime,next_eventname,next_ReasonCode
FROM (SELECT ast.*
             lead(EventName) over (partition by EventName order by DateTime) as next_eventname,lead(ReasonCode) over (partition by ReasonCode order by DateTime) as next_ReasonCode
      FROM ucce1_awdb.dbo.Agent_State_Trace ast
     ) ast
WHERE EventName = 3 and
      ReasonCode= 0 and
      next_eventname = 0 and
      next_ReasonCode = 114
,

您不能使用select子句的where子句中定义的别名...,也不能使用where子句中的窗口函数。您需要将过滤移至外部查询:

SELECT *
FROM (
    SELECT 
        SkillTargetID,lead(EventName,1) 
            over(partition by EventName order by DateTime) as next_eventname,lead(ReasonCode,1) 
            over(partition by ReasonCode order by DateTime) as next_ReasonCode
    FROM ucce1_awdb.dbo.Agent_State_Trace ast
) t
WHERE 
    EventName = 3 
    AND ReasonCode= 0
    AND next_eventname = 0 
    AND next_ReasonCode = 114

请注意,我将 all 个过滤器移到了外部查询(不仅是那些应用于窗口计算的过滤器):那是因为(可能!)您需要窗口函数来查看整个数据集,在应用过滤器之前。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...