在SQL中计算期末余额和期初余额

时间:2018-11-09 12:53:52

标签: sql sql-server

我有一张表'transactions(txDate,amount,txType),其中txType可以“贷记”或“借记”。 在两个日期之间退还交易时,我需要获得期初和期末余额。

结果的第一行应为期初余额,然后是日期之间的所有tx列表,最后一行应为期末余额

获取列表并不是火车粉碎,但为了平衡,我目前有以下

SELECT SUM(amount) AS [Opening Balance]
FROM 
(
    SELECT SUM([Amount]) amount
    FROM [dbo].[Transaction]
    WHERE [txDate] <= @startDate
    AND [txType] = 'credit'

    UNION ALL

    SELECT 0 - SUM([Amount]) amount
    FROM [dbo].[Transaction]
    WHERE [TransactionDate] <= @startDate
    AND [txType] = 'debit'
) Transactions

这比应有的数量大得多。

对于期末余额,我不知道该如何处理

1 个答案:

答案 0 :(得分:1)

您可以在CASE中使用SUM

select  sum(case when txType = 'credit' and transactionDate <= @startDate 
                then amount end) - 
        sum(case when txType = 'debit' and transactionDate <= @startDate 
                then amount end)[Opening Balance],
        sum(case when txType = 'credit' and transactionDate <= @endDate 
                then amount end) - 
        sum(case when txType = 'debit' and transactionDate <= @endDate 
                then amount end)[Closing Balance]
from transaction