【问题标题】:Extracting account's transactions with no other transactions with this counterparty提取账户的交易,与该交易对手没有其他交易
【发布时间】:2019-12-11 15:45:45
【问题描述】:

我有一个包含帐户交易的数据库。对我来说相关的列是: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 的 sn-p 以便更好地理解:

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 distinct?

【问题讨论】:

  • EXISTS 浮现在脑海中。

标签: sql sql-server database tsql


【解决方案1】:

您可以添加带有相关子查询的not exists 条件,以确保相同的Account 在过去21 天内没有具有相同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)
    )

【讨论】:

  • 感谢您的快速响应和帮助,如果我的数据集包含 2 个这样的表之间的内部联接 - 从 myTable a 内部联接 myTable2 b 在 a.Account = b.Account 上,我该如何命名我作为一个表做的连接,以及如何在存在子查询上命名它?
  • @elads11:我回答了您提出的问题...如果您还有其他问题,那么您最好问一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-21
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 2015-08-27
相关资源
最近更新 更多