首页 > 解决方案 > 提取账户的交易,与该交易对手没有其他交易

问题描述

我有一个包含帐户交易的数据库。对我来说相关的列是: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不同?

标签: sqlsql-serverdatabasetsql

解决方案


您可以添加一个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)
    )

推荐阅读