sql - 根据当前行的条件计算前 24 个月的行
问题描述
如何根据 principalreliefflag 从当前行计算前 24 个月(它应该基于每一行(每个月与前 24 个月)。所以从当前行计算主要标志(Y)到前 24 个月。)?
我拥有的数据:
我需要的数据:
代码:
-------------------------------------------------------------------------
----Identify customers who are on principal relief more than one month
-------------------------------------------------------------------------
IF OBJECT_ID('tempdb..##PRappliedmorethan_once') IS NOT NULL
DROP TABLE ##PRappliedmorethan_once
select *,
case when PrincipalReliefFlag='Y' then 1 else 0
end PR_applied_months
into ##PRappliedmorethan_once
from ##TL_details_dates2
IF OBJECT_ID('tempdb..##PRappliedmorethan_once1') IS NOT NULL
DROP TABLE ##PRappliedmorethan_once1
select *,
--Identify customers who have applied for principal relief within the past 12 months
sum(PR_applied_months) over (partition by productitemcode, productcode
order by dim_snapshotdate_key
rows between 23 preceding and current row
)
abcd
into ##PRappliedmorethan_once1
from ##PRappliedmorethan_once
它有效,但有没有更好的方法?
解决方案
尝试使用该DATEDIFF()
功能检查过去 24 个月,例如:
SELECT COUNT(*) FROM YOUR_TABLE
WHERE DATEDIFF(month, current_row_date, date_to_be_compared) <= 24
推荐阅读
- javascript - 在 javascript/typescript 中过滤 json
- typescript - 如何在 OOP 类中保存状态?
- java - 自定义 ListView 中的滚动滞后
- javascript - 如何使用 Bootstrap 多选选项将样式和 onEachFeature 函数添加到多个 L.GeoJSON.AJAX 图层?
- python - 仅使用证书的 ldap 身份验证
- python - 我应该如何导入以数字为名称的python目录?
- java - Anroid webview中的Google Login(OAuth2.0)卡在“请稍等...”
- javascript - Heroku一直超时:等待网络时出错:资源暂时不可用
- webpack - 使用 Angular CLI 构建的 yarn 与 npm 的性能显着下降
- jupyter-notebook - 已经在 Jupiter 笔记本上安装了 R 时,如何自动建议或自动更正?