0
繼我從昨天最初提出的問題(here)後,我能夠構建下面的SQL查詢,該查詢生成了運行的發票和付款清單。如何獲取此查詢中的實際運行餘額
SELECT
'Invoice' AS TransactionType,
i.InvoiceNumber AS Description,
i.InvoiceDate AS TransactionDate,
CAST(ROUND(i.OutstandingBalance, 2) AS DECIMAL(12, 2)) AS TransactionAmount
FROM
Invoices i
WHERE
i.CustomerId = 12
AND i.InvoiceDate BETWEEN '20150601' AND '20160229'
AND i.OutstandingBalance > 0.02
UNION
SELECT
'Payment' AS TransactionType,
ip.InvoicePaymentId AS Description,
ip.InvoicePaymentDate AS TransactionDate,
- ip.Amount AS TransactionAmount
FROM
InvoicePayments ip
WHERE
ip.CustomerId = 12
AND ip.InvoicePaymentDate BETWEEN '20150601' AND '20160229'
ORDER BY
TransactionDate
我現在想要做的是產生一個額外的列,它實際上是帳戶上的運行餘額。我想,如果我開始使用一個變量,那麼應該可以添加(或從中減去給我的東西)。爲此,我嘗試了以下內容;
DECLARE @OutstandingBalance MONEY = 0
SELECT
'Invoice' AS TransactionType, i.InvoiceNumber AS Description,
i.InvoiceDate AS TransactionDate,
CAST(ROUND(i.OutstandingBalance, 2) AS DECIMAL(12, 2)) AS TransactionAmount,
@OutstandingBalance + CAST(ROUND(i.OutstandingBalance, 2) AS DECIMAL(12, 2)) AS Balance
FROM
Invoices i
WHERE
i.CustomerId = 12
AND i.InvoiceDate BETWEEN '20150601' AND '20160229'
AND i.OutstandingBalance > 0.02
哪產生了下面的結果。
但是試圖通過使它@OutstandingBalance + =像這樣修改的查詢;
DECLARE @OutstandingBalance MONEY = 0
SELECT
'Invoice' AS TransactionType, i.InvoiceNumber AS Description,
i.InvoiceDate AS TransactionDate,
CAST(ROUND(i.OutstandingBalance, 2) AS DECIMAL(12, 2)) AS TransactionAmount,
@OutstandingBalance += CAST(ROUND(i.OutstandingBalance, 2)AS DECIMAL(12,2)) AS Balance
FROM
Invoices i
WHERE
i.CustomerId = 12
AND i.InvoiceDate BETWEEN '20150601' AND '20160229'
AND i.OutstandingBalance > 0.02
拋出一個錯誤告訴我,語法附近關鍵字AS(這我相信所指的平衡不正確。我懷疑,我應該是「設置」的@OutstandingBalance
價值,但加入中的一組語句選擇也會引發錯誤。
是否有可能在這種查詢的創建運行平衡,如果是一個人如何適應設置@OutstandingBalance
實現呢?
針對低於這個答案是結果集我得到:
編輯 修訂查詢以適應發票和付款:
SELECT 'Invoice' AS TransactionType,
i.InvoiceNumber AS Description,
i.InvoiceDate AS TransactionDate,
CAST(ROUND(i.OutstandingBalance,2)AS DECIMAL(12,2)) AS TransactionAmount ,
SUM(CAST(ROUND(i.OutstandingBalance,2)AS DECIMAL(12,2))) OVER(ORDER BY i.InvoiceDate, i.InvoiceNumber) AS Balance
FROM Invoices i
WHERE i.CustomerId = 12
AND i.InvoiceDate BETWEEN '20150601' AND '20160229'
AND i.OutstandingBalance > 0.02
UNION
SELECT
'Payment' AS TransactionType,
ip.InvoicePaymentId AS Description,
ip.InvoicePaymentDate AS TransactionDate,
- ip.Amount AS TransactionAmount,
SUM(CAST(ROUND(-ip.Amount,2) AS DECIMAL(12,2))) OVER(ORDER BY ip.InvoicePaymentDate,ip.InvoicePaymentId) AS Balance
FROM InvoicePayments ip
WHERE ip.CustomerId = 12
AND ip.InvoicePaymentDate BETWEEN '20150601' AND '20160229'
ORDER BY TransactionDate, Description
將會產生如下:
Zohar的,謝謝你的回答,我沒有了以前讓我學到新的東西碰到過,總是好的!我跑了你的兩條建議,並附上結果的屏幕截圖到我的問題。首先,最終的結果幾乎是正確的(這是一分錢,但是會在某個地方湊到一起),但爲什麼平衡不會在每條線上增加?其次,是否可以將相同的邏輯應用於餘額顯示按付款額減少的付款? –
我是一個白癡,它在一天結束時總結,是完美的,只需要嘗試付款方面。 –
我剛剛注意到日期不是唯一的。我想你應該在查詢和'over'子句中將'incodeNumber'添加到order by子句。看到我編輯的答案。 –