获得期初余额

时间:2018-03-27 10:06:15

标签: sql sql-server

我有这个表以及样本数据。我想根据数据库中的数据计算期初余额。

DROP TABLE VoucherPayment;
CREATE TABLE VoucherPayment
(
VoucherID Int,
VoucherName nvarchar(25),
Credit int,
Debit int,
VoucherDate date
);

INSERT INTO VoucherPayment VALUES (1, 'Cash Payment', '2000', NULL, '2017-12-09');
INSERT INTO VoucherPayment VALUES (2, 'Cash Payment', NULL, '1900', '2017-12-15');
INSERT INTO VoucherPayment VALUES (3, 'Cash Payment', '5680', NULL, '2017-12-19');
INSERT INTO VoucherPayment VALUES (4, 'Cash Receipt', '1200', NULL, '2017-12-20');

我写了一个查询,它在某种程度上提供了输出权。

WITH CTE AS (
    SELECT 
    VoucherID, VoucherName, SUM(Debit) [DrAmount], SUM(Credit) [CrAmount]

    FROM 
    VoucherPayment

    WHERE 
    [VoucherDate] BETWEEN CAST('Dec  1 2017 12:00AM' AS DATE) AND CAST('Dec 30 2017 12:00AM' AS DATE)
    GROUP BY 
    VoucherName, VoucherID

)
SELECT *,
        SUM(ISNULL(DrAmount, 0)+ISNULL(CrAmount, 0)) OVER (ORDER BY VoucherID 
                  ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as Amount

FROM CTE

此查询给出的输出是

VoucherID   VoucherName               DrAmount    CrAmount    Amount
----------- ------------------------- ----------- ----------- -----------
1           Cash Payment              NULL        2000        2000
2           Cash Payment              1900        NULL        3900
3           Cash Payment              NULL        5680        9580
4           Cash Receipt              NULL        1200        10780

如果我将日期更改为12月19日,我将收到此输出

VoucherID   VoucherName               DrAmount    CrAmount    Amount
----------- ------------------------- ----------- ----------- -----------
3           Cash Payment              NULL        5680        5680
4           Cash Receipt              NULL        1200        6880

相反,我希望它像这样

VoucherID   VoucherName      DrAmount    CrAmount    Amount    Opening
----------- ---------------- ----------- ----------- --------- ---------
3           Cash Payment     NULL        5680        9580      3900
4           Cash Receipt     NULL        1200        10780     9580

1 个答案:

答案 0 :(得分:1)

试试这个:

;WITH CTE AS (
    SELECT 
    VoucherID,VoucherDate, VoucherName, SUM(Debit) [DrAmount], SUM(Credit) [CrAmount]
   FROM VoucherPayment
   --WHERE [VoucherDate] BETWEEN CAST('Dec  01 2017 12:00AM' AS DATE) AND CAST('Dec 30 2017 12:00AM' AS DATE)
    GROUP BY VoucherName,VoucherDate, VoucherID
)
SELECT VoucherID, VoucherName,D.DrAmount,D.CrAmount,D.Amount,D.Amount-D.CrAmount [Opening]
FROM(
    SELECT *,
            SUM(ISNULL(DrAmount, 0)+ISNULL(CrAmount, 0)) OVER (ORDER BY VoucherID 
                     ) as Amount
    FROM CTE
    )D
WHERE [VoucherDate] BETWEEN CAST('Dec  19 2017 12:00AM' AS DATE) AND CAST('Dec 30 2017 12:00AM' AS DATE)

<强>输出:

VoucherID   VoucherName     DrAmount    CrAmount    Amount  Opening
3           Cash Payment    NULL        5680        9580    3900
4           Cash Receipt    NULL        1200        10780   9580