sql - 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。
解决方案
是的,这是可能的,您只需在查询中稍作更改即可比较月份的差异。我假设为 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
推荐阅读
- flutter - 不为空时在 TextField 中显示图标
- json - 不区分大小写引用键
- database - 如何在 sqlite3 中跟踪查询速度?
- java - Android:如何让我的蓝牙扫描在给定时间后完成?
- python - 将 pandas 数据框隐蔽到 numpy 数组,必要时插入 np.nan
- c# - C#:将基类集合对象复制到派生类对象中
- javascript - 用于将两个不同字段复制到剪贴板的两个按钮
- java - Java正则表达式中字符串的单个数字
- java - 无法读取 ZipFile.getInputStream(ZipEntry) 方法返回的 ZipInputStream
- kubernetes - Kubernetes:如何在 Google Kubernetes Engine (gke) 中为 kube-controller-manager 添加标志