2012-09-18 53 views
1

我爲信用卡公司工作。我們的數據庫有一個客戶表和一個交易表。客戶表中的字段是SSN和CustomerKey。交易表中的字段是CustomerKey,交易日期(Transdate)和交易金額(TransAmt)。上市交易超過總和閾值

我需要一個報告,可以列出的每個事務對於其中交易的總和在2012年

這裏量> 1000進行了兩天的期間內每個SSN是在事務表的原始數據的示例:

Trans#-----CustKey-----Date--------Amount 
1-----------12345----01/01/12--------$600 
2-----------12345----01/02/12--------$500 
3-----------67890----01/03/12--------$700 
4-----------12345----04/01/12--------$600 
5-----------67890----04/02/12--------$600 

這裏是在客戶表的原始數據的示例:

CustKey-----SSN 
12345------123456789 
67890------123456789 

下面是我所需要的結果:

Trans#------SSN---------Date---------Amount---Group Key 
1--------123456789----01/01/12---------$600--------1 
2--------123456789----01/02/12---------$500--------1 
2--------123456789----01/02/12---------$500--------2 
3--------123456789----01/03/12---------$700--------2 
4--------123456789----04/01/12---------$600--------3 
5--------123456789-----04/02/12--------$600--------3 

正如您在我的結果中看到的,Trans#2列出了兩次,因爲它是兩天內超過$ 1000的一組交易的一部分。超過1000的每組交易都由組密鑰標識。

+0

哪個DBMS和版本? – RichardTheKiwi

+0

請原諒我的無知,但我認爲它是Microsoft SQL Server Management Studio 2008。 – egerencher

回答

0

假設您沒有超前/滯後功能,我的方法如下。

首先,確定符合條件的日期對。您可以通過自我加入來查找符合條件的日期對的交易。現在,你有日期的描述,但這些是在一行而不是在兩行。

因此,您需要將其加入交易。先在第一次約會,然後在第二次約會再次。如果滿足多個條件,則此雙連接(實際上是左外連接)將允許事務出現多次。

這裏是試圖這樣的查詢:

with pairs as 
    (select t.trans, t.ssn, min(date) as mindate, max(date) as maxdate 
     from (select t.*, c.ssn 
      from transaction t join 
       customer c 
       on t.custkey = c.custkey 
      ) t join 
      (select t.*, c.ssn 
      from transaction t join 
       customer c 
       on t.custkey = c.custkey 
      ) tnext 
      on t.ssn= tnext.ssn and 
       t.date = tnext.date - 1 
     group by t.trans, t.ssn, t.amount 
     having sum(t.amount) > 1000 
    ) pairs 
select t.trans, c.ssn 
from transactions t. join 
    customer c 
    on t.custkey = c.custkey left outer join 
    pairs pfirst 
    on t.date = pfirst.mindate and 
     c.custkey = pfirst.custkey left outer join 
    pairs plast 
    on t.date = plast.maxdate and 
     c.custkey = plast.custkey