2

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

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

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

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)(尽管我仍在查看第三个链接),但我希望你们能帮助我。

4

1 回答 1

2

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

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 

见 sqlfiddle

于 2013-01-29T10:23:51.990 回答