我正在使用两个表来显示此数据,其中一个表名为Purchcase_Table
,第二个表为Credit_Book
。
我想要以下结果:
ID Date Descripion Total Paid Balance Running Balance
------------------------------------------------------------------------
1 28-Jan-17 Purchase 1000 6000 4000 4000
1 29-Jan-17 Purchase 5000 4000 1000 5000
1 30-Jan-17 P.Voucher 5000 2000 3000 3000
1 01-Feb-17 Purchase 9000 4000 5000 8000
1 02-Feb-17 Purchase 1500 1000 500 8500
请注意P.Voucher
条目已经在我们发出信用卡付款凭证时计算总运行余额,因此在运行余额中我们看到“3000”作为运行余额,您可以看到其总数,即上一个条目的总运行余额
到目前为止我尝试的是这个,但没有运气
CREATE PROCEDURE [dbo].[usp_Ledger]
(@VenId Int)
AS
BEGIN
DECLARE @Ledger TABLE (ID INT,
[DATE] DATETIME,
[DESCRIPTION] NVARCHAR(350),
TRANSACTION_TYPE NVARCHAR(50),
TOTAL DECIMAL(18,2),
PAID DECIMAL(18,2),
BALANCE DECIMAL(18,2),
RUNNING_BALANCE DECIMAL(18,2)
)
INSERT INTO @Ledger
SELECT
[Ven_Id], [Pur_Date], '(PURCHASE)', 'P',
[Grand_Total], [Paid], [Balance], 0
FROM
[dbo].[Purchase_Table] pc
INNER JOIN
[dbo].[Vendor] av ON av.ID = pc.Ven_Id
/* P REFERS TO PURCHASE TRANSACTION AND CPV REFERS TO CREDIT PURCHASE VOUCHER */
UNION
SELECT
[VenId], [TransactionDate], '(VENDOR PAYMENT VOUCHER)', 'CPV',
[OriginalAmount], [PaidAmount], [RunningBalance], 0
FROM
[dbo].[Credit_Book] vcb
INNER JOIN
[dbo].[Vendor] av ON av.ID = vcb.VendorId
SELECT
ID, [DATE], [DESCRIPTION],
TOTAL_AMOUNT, PAID_AMOUNT,
BALANCE_AMOUNT,
CASE TRANSACTION_TYPE
WHEN 'P'
THEN LAG([BALANCE_AMOUNT], 1, 0) OVER (ORDER BY [DATE]) + [BALANCE_AMOUNT]
WHEN 'CPV'
THEN [BALANCE_AMOUNT]
END AS RUNNING_BALANCE
WHERE
ID = @VendorId
ORDER BY
[DATE]
END
我得到的结果就是这个
ID Date Descripion Total Paid Balance Running Balance
------------------------------------------------------------------------
1 28-Jan-17 Purchase 1000 6000 4000 4000
1 29-Jan-17 Purchase 5000 4000 1000 5000
1 30-Jan-17 P.Voucher 5000 2000 3000 3000
1 01-Feb-17 Purchase 9000 4000 5000 8000
1 02-Feb-17 Purchase 1500 1000 500 5500
您可以在最后一个条目中查看其添加的最后余额金额与当前余额金额并显示错误结果。它应该是8500。
我知道我的问题太长了,也可能会让人感到困惑,但以防万一有人为此提供了解决方案。