SQL - 使用基于列值的滞后函数比较 table 中的行

SQL - Comparing rows in table with lag function based on column values

我正在尝试创建一个名为 previous_month 的列,如果 month_in 比当前行少一个月,它会根据不同 type/id 的组查看上一行行,如果是 previous_month = True,否则为 False。

type    id  month_in    previous_month
a       1   2019-09-01  FALSE
a       1   2019-10-01  TRUE
a       1   2019-11-01  TRUE
a       1   2020-02-01  FALSE
a       2   2020-01-01  FALSE
a       2   2020-02-01  TRUE

我试过使用滞后函数

Select 
       type, 
       id,
       month_for,
       lag(True, 1, False) over (partition by type, id order by type, id, month_for) as previous_month

from myTable

然而,当 month_in 增加超过一个月时,这并没有说明,即我得到这个 table:

type    id  month_in    previous_month
a       1   2019-09-01  FALSE
a       1   2019-10-01  TRUE
a       1   2019-11-01  TRUE
a       1   2020-02-01  TRUE
a       2   2020-01-01  FALSE
a       2   2020-02-01  TRUE

关于滞后函数是否可行,有什么建议吗?或者如果不是实现此目标的最有效方法?我在雪花 sql 工作。

您可以使用自联接和 "not exists"

Select 
       a.type, 
       a.id,
       a.month_in,  
       case 
        when datediff(month, a.month_in, b.month_in)= -1 Then 'TRUE'
        else 'False' end as previous_month  

from myTable a left join myTable b on a.type = b.type and a.id = b.id and a.month_in > b.month_in
and not exists
(
  select 1 from myTable c where a.type = c.type and a.id = c.id
  and c.month_in > b.month_in and c.month_in < a.month_in 
)

输出:

type    id  month_in    previous_month
a   1   2019-09-01  False
a   1   2019-10-01  TRUE
a   1   2019-11-01  TRUE
a   1   2020-02-01  False
a   2   2020-01-01  False
a   2   2020-02-01  TRUE

是的,这是可能的,您只需对查询稍作更改即可比较月份的差异。我假设为 SQL 服务器。您只需要确保前一行和当前行的差异在 1 个月内

Select 
       type, 
       id,
       month_for,
       case when datediff(month,  lag(month_for, 1) over (partition by type, id order by type, id, month_for), month_for) = 1 then 'TRUE' ELSE 'FALSE' as previous_month

from myTable