Db2 LAG 函数可以引用自身吗?

Can Db2 LAG function refer to itself?

我正在尝试通过复制此 Excel 公式来输入信息以识别 GROUP ID:

IF(OR(A2<>A1,AND(B2<>"000",B1="000")),D1+1,D1)

这个公式是在我的光标在“D2”的时候写的,意思是我参考了上一行新增的列值生成了当前值。

我想使用 Db2 SQL,但我不确定该怎么做,因为我需要在要添加的列上执行 LAG 函数并引用它们的值。

如有更好的方法,敬请指教

谢谢。

您需要嵌套 OLAP-functions,假设 ORDER BY SERIAL_NUMBER, EVENT_TIMESTAMP returns Excel:

中显示的顺序
with cte as 
 (
    select ...
       case --IF(OR(A2<>A1,AND(B2<>"000",B1="000"))
         when (lag(OPERATION)
              over (order by SERIAL_NUMBER, EVENT_TIMESTAMP) = '000'
              and OPERATION <> '000')
           or lag(SERIAL_NUMBER,1,'')
              over (order by SERIAL_NUMBER, EVENT_TIMESTAMP) <> SERIAL_NUMBER
         then 1
         else 0
       end as flag -- start of new group
    from tab
 ) 
select ...
   sum(flag)
   over (order by SERIAL_NUMBER, EVENT_TIMESTAMP
         rows unbounded preceding) as GROUP_ID
from cte

您的代码正在计算数据中“中断”的次数,其中“中断”定义为 000 或第一列中的值发生变化。

在SQL中,您可以将此作为累加和:

select t.*,
       sum(case when prev_serial_number = serial_number or operation <> '000'
                then 0 else 1
           end) over (order by event_timestamp rows between unbounded preceding and current row) as column_d
from (select t.*,
             lag(serial_number) over (order by event_timestamp) as prev_serial_number
      from t
     ) t