嗨,我写了一封SQL给我剩余的发票付款 REST =(发票总额 - 付款)
我有什么:
Invoice_ID|Invoice Total | Payment | REST
----------|----------------|-----------|---------
01 |93 | 10 | 69
01 |93 | 9 | 69
01 |93 | 5 | 69
这就是我得到的,它是正确的,但我真正想要的是递归REST
Invoice_ID|Invoice Total | Payment | REST
----------|----------------|-----------|---------
01 |93 | 10 | 83
01 |93 | 9 | 74
01 |93 | 5 | 69
答案 0 :(得分:1)
尝试如下。在“付款”列上运行总计,并使用您的发票金额减去该值。
SELECT Invoice_ID,InvoiceTotal ,Payment,
InvoiceTotal- Sum(payment)
OVER (
partition BY Invoice_ID
ORDER BY rno) rest
FROM (SELECT *,
Row_number()
OVER (
partition BY Invoice_ID
ORDER BY Invoice_ID) rno
FROM table_name)a
答案 1 :(得分:0)
CREATE TABLE #Table(Id INT IDENTITY(1,1),Invoice_ID INT,InvoiceTotal
INT,Payment INT,REST INT)
INSERT INTO #Table(Invoice_ID ,InvoiceTotal ,Payment ,REST)
SELECT 01,93,10,69 UNION ALL
SELECT 01,93,9,69 UNION ALL
SELECT 01,93,5,69
;WITH CTE (_Id ,_InvoiceID ,_InvoiceTotal ,_Payment ,_REST )AS
(
SELECT Id ,Invoice_ID ,InvoiceTotal ,Payment ,(InvoiceTotal - Payment)
FROM #Table WHERE Id = 1
UNION ALL
SELECT Id ,Invoice_ID ,InvoiceTotal ,Payment ,_REST - Payment
FROM #Table
JOIN CTE ON CTE._InvoiceID = #Table.Invoice_ID
WHERE _Id = Id - 1
)
SELECT * FROM CTE