Oracle SQL查询按组获取剩余金额

时间:2013-01-29 10:12:44

标签: sql oracle

我需要为每个信用卡号找到剩余金额。预期的结果是:

CREDIT_NO   CREDIT_TYPE CREDIT_AMOUNT   TOTAL_A REMAINING_AMT   FINAL_TOTAL_PER_BILL
A1          W           100             1000     900            600
A1          X           100             1000     800            600
A1          Y           100             1000     700            600
A1          Z           100             1000     600            600
B1          X           100             2000     1900           1700
B1          Y           100             2000     1800           1700
B1          Z           100             2000     1700           1700

这是我到目前为止所做的查询(请原谅noob):

WITH TEMP AS
  (SELECT 1 ID,
    'A1' CREDIT_NO,
    'X' CREDIT_TYPE,
    100 CREDIT_AMOUNT,
    1000 TOTAL_A
  FROM DUAL
  UNION ALL
  SELECT 2, 'A1' , 'Y', 100, 1000 FROM DUAL
  UNION ALL
  SELECT 4, 'A1' , 'Z', 100, 1000 FROM DUAL
  UNION ALL
  SELECT 3, 'B1', 'X', 100, 2000 FROM DUAL
  UNION ALL
  SELECT 5, 'B1', 'Y', 100, 2000 FROM DUAL
  UNION ALL
  SELECT 6, 'B1', 'Z', 100, 2000 FROM DUAL
  UNION ALL
  SELECT 7, 'A1', 'W', 100, 1000 FROM DUAL
  )

SELECT 
  TEMP1.CREDIT_NO ,
  TEMP1.CREDIT_TYPE,
  TEMP1.CREDIT_AMOUNT ,
  TEMP1.TOTAL_A ,
  CASE
    WHEN TEMP1.CREDIT_NO  = (LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) ) -- set remaining CREDIT_AMOUNT
    OR (LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) ) IS NULL
    THEN TEMP1.TOTAL_A - (SUM(TEMP1.CREDIT_AMOUNT) OVER ( ORDER BY TEMP1.CREDIT_NO ROWS BETWEEN
      UNBOUNDED PRECEDING
    AND CURRENT ROW ) )
    WHEN TEMP1.CREDIT_NO <>   -- new bill, new total CREDIT_AMOUNT
      (LAG (TEMP1.CREDIT_NO,1) OVER (ORDER BY TEMP1.CREDIT_NO) )
    THEN TEMP1.TOTAL_A - TEMP1.CREDIT_AMOUNT
  END AS REMAINING_AMT 
  ,TEMP1.TOTAL_A - (SUM(TEMP1.CREDIT_AMOUNT) OVER (PARTITION BY CREDIT_NO)) AS FINAL_TOTAL_PER_BILL
FROM TEMP TEMP1
ORDER BY CREDIT_NO, CREDIT_TYPE

我的问题是我不知道如何计算第二个信用额的剩余金额。上述查询的结果是:

CREDIT_NO   CREDIT_TYPE CREDIT_AMOUNT   TOTAL_A REMAINING_AMT   FINAL_TOTAL_PER_BILL
A1          W           100             1000     900            600
A1          X           100             1000     800            600
A1          Y           100             1000     700            600
A1          Z           100             1000     600            600
B1          X           100             2000     1900           1700
B1          Y           100             2000     1400           1700
B1          Z           100             2000     1300           1700

是否可以在不使用存储过程的情况下获得剩余运行量?我尝试将它基于rownum,但它不是顺序的。

即使我发现了类似的问题(Link 1Link 2Link 3) (我现在仍然会通过第三个链接),我希望你们能帮助我。

1 个答案:

答案 0 :(得分:2)

使用运行小计,并注意partition子句:

select credit_no, credit_type, 
   total_a - sum(credit_amount) over (partition by credit_no order by id) as remaining_credit,
   total_a,
   total_a - sum(credit_amount) over (partition by credit_no) as FINAL_TOTAL_PER_BILL
from temp 

see sqlfiddle