SQL - LEAD() 函数

Posted

技术标签:

【中文标题】SQL - LEAD() 函数【英文标题】:SQL - LEAD() Function 【发布时间】:2020-08-24 20:58:54 【问题描述】:

我尝试使用以下代码:

 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,我无法执行该查询。有人可以告诉我应该如何处理吗?

【问题讨论】:

lead(EventName,1) over (partition by EventName 没用,eventname 在同一个 PARTITION 中永远不会改变(目前它与where event_name = 0 非常相似)。 next_reason_cde 也一样。你能展示一些示例数据和预期结果吗? 【参考方案1】:

你需要一个子查询:

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

【讨论】:

【参考方案2】:

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

SELECT *
FROM (
    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
) t
WHERE 
    EventName = 3 
    AND ReasonCode= 0
    AND next_eventname = 0 
    AND next_ReasonCode = 114

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

【讨论】:

以上是关于SQL - LEAD() 函数的主要内容,如果未能解决你的问题,请参考以下文章

SQL windows 函数 LEAD/LAG 但只考虑某些值?

sql SQL Server 2012 TSQL新函数LAG,LEAD,FIRST_VALUE和LAST_VALUE

SQL查询获取同一字段前/后n行的值_lag/lead

在sqlserver 2008 怎么配置才可以正常支持lead和lag分析函数

Hive分析函数LAG和LEAD详解

如何为不同的观察组使用 LAG 和 LEAD 窗口函数