sql - 提取账户的交易,与该交易对手没有其他交易
问题描述
我有一个包含帐户交易的数据库。对我来说相关的列是:Account、Amount、Date、description 和 Transaction_Code。我的目标是为给定帐户提取符合我的触发点的行。我写成功的触发点是Amount大于200和Transaction_Code in ('1,'2','3')。我正在努力解决的唯一触发点是:该帐户在过去 21 天内与该交易对手没有其他交易。我只成功地选择了我需要的日期范围。数据集示例:
**Account** **Amount** **Date** **Description** **Transaction_Code**
555 280 2019-10-06 amt_fee 1
555 700 2019-09-20 refund 2
555 250 2019-10-01 amt_fee 1
我为示例编写的 sql 片段以便更好地理解:
select Account, Amount, Date, Description
from MyTable
where Account = '555' and Date between '2019-09-15' and '2019-10-06'
and Amount >= 200
and Transaction_Code in ('1','2','3')
我遇到的问题是如何做到以下条件:''该帐户在过去 21 天内与该交易对手没有其他交易。'' 交易对手是指描述或交易代码列。我应该如何为我真正的更大数据集做这个条件?与groupby和count不同?
解决方案
您可以添加一个not exists
带有相关子查询的条件,以确保在过去 21 天内Account
没有相同Description
或相同的事务。Transaction_Code
select Account, Amount, Date, Description
from MyTable t
where
Account = '555' and Date between '2019-09-15' and '2019-10-06'
and Amount >= 200
and Transaction_Code in (1, 2, 3)
and not exists (
select 1
from MyTable t1
where
t1.Account = t.Account
and (t1.Description = t.Description or t1.Transaction_Code = t.Transaction_Code)
and t1.date < t.date
and t1.date >= dateadd(day, -21, t.date)
)
推荐阅读
- php - 为什么当我使用 Route::domain()->group() 时没有设置 cookie?
- ros - 如何将 ROS 包传递给其他人?
- javascript - Vue.js 中的条件类样式绑定
- python-3.x - 如何在条件为真之前获得 50 行的值
- kubernetes - 如何在 kube-prometheus-stack 中添加 Grafana 的预置通知通道?
- android - 使用不同大小的标签时,有没有办法将域标签向左移动?
- javascript - JQuery如何等到元素和子节点被加载?
- javascript - Google 应用脚本触发器在创建后不会触发
- mysql - 在重复键上
- java - 等待多个正在运行的线程中的一个线程