负余额

时间:2017-01-16 22:53:38

标签: function plsql aggregate

我有3张桌子。帐户。 Trans and Balance。

Trans表中的Sum(Amount)等于每个帐户在任何给定时间的余额。

我需要一个查询,检查从今天起的连续3个月或更长时间内的余额为负数。 (所以每当我运行它时都是sysdate。)

我想知道我怎样才能查询显示帐号和余额的位置,只有在连续3个月或更长时间内显示为负数时,无论交易何时发生。

表:

Trans Table
Select * from trans where accountid = 1;

Transdate  Merchant    Amount   AccountID
10/1/16    Employer    50       1
10/4/16    Walmart     -20      1
10/7/16    Kroger      -50      1

现在,他的帐户出现了负数 - 2016年10月7日20美元。

Transdate  Merchant    Amount   AccountID
12/01/16   Employer    10       1

他的帐户仍然是负面的。如果我今天(2017年1月16日)或之后运行查询,他的帐户应该被拿起,因为他仍然有至少90天的负余额。

Balance Table

每个帐户只保留1条记录。截至今天,它显示以下内容:

AccountID    Balance    LastUpdate
1            -10        12/01/2016

LastUpdate与该帐户的Trans Table中最后一个交易日期相同。

1 个答案:

答案 0 :(得分:2)

尝试以下方法。顶部只是创建了一些测试数据......

 WITH 
 trans (transdate,merchant,amount,accountID)
 AS
 (SELECT sysdate-100,'A',100,1 FROM dual UNION ALL
  SELECT sysdate-99,'B',-101,1 FROM dual UNION ALL
  SELECT sysdate-91,'C',-50,1 FROM dual UNION ALL
  SELECT sysdate-10,'D',30,1 FROM dual UNION ALL
  SELECT sysdate-100,'E',100,2 FROM dual UNION ALL
  SELECT sysdate-99,'F',-100,2 FROM dual UNION ALL
  SELECT sysdate-91,'G',-50,2 FROM dual UNION ALL
  SELECT sysdate-10,'H',200,2 FROM dual UNION ALL
  SELECT sysdate-10,'I',100,3 FROM dual UNION ALL
  SELECT sysdate-9,'J',-50,3 FROM dual UNION ALL
  SELECT sysdate-8,'K',-75,3 FROM dual 
 )
SELECT DISTINCT
 accountId
FROM
 (SELECT
   accountid
  ,transdate
  ,amount
   --get the maximum balance in the dataset
  ,MAX(balance) OVER (PARTITION BY accountID) max_balance
  FROM
   --this query gets raw transaction data and calculates cumulative balance
   (SELECT
     accountid
    ,transdate
    ,amount
     --cumulative balance
    ,SUM(amount) OVER (PARTITION BY accountID ORDER BY transdate)   balance   
     --works the dateof the next transaction - ths determines how long the balance is current 
    ,LEAD(transdate) OVER (PARTITION BY accountID ORDER BY transdate) - 1  bal_end_date
    FROM
     trans
   )
  WHERE 1=1
  --only interested in balances that are 'current' in the past three months
  AND bal_end_date >= ADD_MONTHS(sysdate,-3)
 )
WHERE 1=1
--only want accounts where the maximum balance is negative
AND max_balance < 0
;