sql - 如何查找超过 5 年期间超过设定金额的记录
问题描述
我正在尝试在自 2011 年 1 月 1 日以来的任何 5 年期间内提供超过 5000 的财务表中查找 contact_numbers。我在兜圈子。
这就是我所拥有的,但它从 2011 年开始计算一切。任何帮助都会很棒!
select t1.contact_number,
sum(Amount) as amount
from batch_transactions t1
inner join contacts c on c.contact_number = t1.contact_number
cross apply (
select sum(amount) Rolling_sum
from batch_transactions
where contact_number = t1.contact_number
and datediff(year, transaction_date, t1.transaction_date) <= 5
and transaction_date >= '2011-01-01' and contact_type <> 'O'
and t1.transaction_date >= transaction_date
) o where t1.transaction_date >= '2011-01-01' and contact_type <> 'O'
and datediff(year, transaction_date, t1.transaction_date) <= 5
group by t1.contact_number
having sum(amount) > 5000
order by contact_number
解决方案
我认为你希望这个结构为:
select c.contact_number, bt2.rolling_sum
from contacts c join
batch_transctions bt
on cross apply
(select sum(bt2.amount) as Rolling_sum
from batch_transactions bt2
where bt2.contact_number = c.contact_number and
bt2.transaction_date >= bt.transaction_date and
bt2.transaction_date < dateadd(year, 5, bt.transaction_date)
) bt2
where bt2.rolling_sum > 5000;
推荐阅读
- php - 在特定文件中搜索一串文本
- node.js - 如何等待stream.write()的循环结束
- c# - 当我上梯子并创建赢功能时如何改变方向
- angular - 将自定义训练模型加载到 ml5 imageClassifier 时模型无效
- java - 新编码器来了!我需要学习如何修复无法找到或加载主类
- javascript - 基于 url 的活动/折叠类不适用于子菜单
- powerbi - 通过 DAX 在 Power BI 中排名倒数 10%
- visual-studio-code - 如何阻止 VSCode 最大化启动?
- assembly - x86_64 - 为什么用 rdtsc/rdtscp 给程序计时会给出不合理的大数字?
- enterprise-architect - 有没有办法使用 Java API 从企业架构模型中获取所有用例图?