2017-08-09 63 views
1

我想在一天內檢索現金存款超過4個合計爲1000000的記錄並持續超過5天。通過在oracle中延續天數檢索記錄

我想出了下面的查詢。

SELECT COUNT(a.txamt) AS "txcount" 
      , SUM(a.txamt) AS "txsum" 
      , b.custcd 
      , a.txdate 
     FROM tb_transactions a 
INNER JOIN tb_accounts b 
     ON a.acctno = b.acctno 
    WHERE a.cashflowtype = 'CR' 
    GROUP BY b.custcd, a.txdate 
    HAVING COUNT(a.txamt)>4 and SUM(a.txamt)>='1000000' 
    ORDER BY a.txdate; 

但我堅持如何獲取記錄如果模式持續5天。

如何達到預期效果?

+2

這是什麼意思? 「一天中現金存款總數超過4個,總計達100萬個,並且持續5天以上」。樣本數據和期望的結果將有所幫助。 –

回答

1

喜歡的東西:

SELECT * 
FROM (
    SELECT t.*, 
     COUNT(txdate) OVER (PARTITION BY custcd 
           ORDER BY txdate 
           RANGE BETWEEN INTERVAL '0' DAY PRECEDING 
              AND INTERVAL '4' DAY FOLLOWING) AS 
num_days 
    FROM (
    select count(a.txamt) as "txcount", 
      sum(a.txamt) as "txsum", 
      b.custcd, 
      a.txdate 
    from tb_transactions a inner join tb_accounts b on a.acctno=b.acctno 
    where a.cashflowtype='CR' 
    group by b.custcd, a.txdate 
    having count(a.txamt)>4 and sum(a.txamt)>=1000000 
) t 
) 
WHERE num_days = 5 
order by a.txdate;