【问题标题】:Same day, same customer but different branch transactions同一天,同一客户,但不同的分行交易
【发布时间】:2020-07-29 09:18:12
【问题描述】:

我有一个表格,其中包含帐号、交易日期、交易分行和金额。

我想生成一个包含以下信息的列:

如果该特定客户在同一天从不同的分支机构进行了交易。

结果示例如下:

    AccountNumber   Transaction_branch  tran_Date   Amount  Different_Branch_Tran
    11452           331                 20/07/2020  500     no
    11452           331                 21/07/2020  500     no
    5432            14                  22/07/2020  500     no
    5432            14                  22/07/2020  500     no
    11452           14                  24/07/2020  500     yes
    11452           420                 24/07/2020  500     yes
    11452           14                  26/07/2020  500     no

如果客户在同一天进行了相同数量的交易,我有一个代码可以显示我。但是我不知道如何修改或更改此代码以获得我想要的结果。

 select 
    a.*,
    case when count(*) over(partition by trandate, accountnumber, amount) > 1 then 'Yes' else 'No' end SameAmountSameDay
from Tran_table  a 
where trandate> '20190701' 

【问题讨论】:

    标签: sql-server count partition case-when


    【解决方案1】:
    .....
    case when 
    min(Transaction_branch) over(partition by AccountNumber, tran_Date, Amount) 
    = 
    max(Transaction_branch) over(partition by AccountNumber, tran_Date, Amount) 
    then 'No' else 'Yes' 
    end as SameAmountSameDayDifferentBranch
    .........
    

    【讨论】:

      【解决方案2】:

      一种方法是使用EXISTS 和子查询,因为您不能在窗口化COUNT 中使用DISTINCT

      SELECT TT.AccountNumber,
             TT.Tranasction_branch,
             TT.tran_date,
             TT.Amount,
             CASE WHEN EXISTS(SELECT 1
                              FROM dbo.Tran_table sq
                              WHERE sq.AccountNumber = TT.AccountNumber
                                AND sq.Tran_Date = TT.Tran_Date
                                AND sq.Tranasction_branch != TT.Transaction_branch) THEN 'Yes' ELSE 'No' END AS Different_Branch_Tran
      FROM dbo.Tran_table TT
      WHERE TT.trandate > '20190701'; --This is called Tran_Date in your sample data, are these different columns?
      

      【讨论】:

      • 尽管它看起来有效,但由于我处理的数据非常大,查询需要太多时间(1h 43m 并且还在继续)
      • 该查询不应该花费那么多时间,除非您严重缺乏索引,@Cemil。
      猜你喜欢
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多