首页 > 解决方案 > SQL - 根据列值将表中的行与滞后函数进行比较

问题描述

我正在尝试创建一个名为的列,该列previous_month基于不同类型/id 的组来查看前一行是否month_in比当前行少一个月,如果是previous_month=真,否则为假。

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增加超过一个月,即我得到这张表:

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。

标签: sqlsnowflake-cloud-data-platform

解决方案


是的,这是可能的,您只需在查询中稍作更改即可比较月份的差异。我假设为 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

推荐阅读