Calculating Closing and Opening Balance in SQL









up vote
0
down vote

favorite












I have a table 'transactions(txDate, amount, txType) where txType can "credit" or "debit".
I need to get an opening and closing balance when returning transactions between two dates.



The first row of the results should be the Opening Balance, then a list of all tx between the dates and the last row to be a Closing balance



Getting the list isn't a train smash but for the balances, I currently have the following



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


this gives a very big amount than what it should be.



And for the Closing balance, I have no idea how to go about it










share|improve this question



















  • 4




    it would be good to include some sample data and expected result for them
    – Radim Bača
    Nov 9 at 12:55






  • 1




    What's a train smash?
    – nicomp
    Nov 9 at 12:57










  • Have you used window functions?
    – Salman A
    Nov 9 at 13:05














up vote
0
down vote

favorite












I have a table 'transactions(txDate, amount, txType) where txType can "credit" or "debit".
I need to get an opening and closing balance when returning transactions between two dates.



The first row of the results should be the Opening Balance, then a list of all tx between the dates and the last row to be a Closing balance



Getting the list isn't a train smash but for the balances, I currently have the following



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


this gives a very big amount than what it should be.



And for the Closing balance, I have no idea how to go about it










share|improve this question



















  • 4




    it would be good to include some sample data and expected result for them
    – Radim Bača
    Nov 9 at 12:55






  • 1




    What's a train smash?
    – nicomp
    Nov 9 at 12:57










  • Have you used window functions?
    – Salman A
    Nov 9 at 13:05












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a table 'transactions(txDate, amount, txType) where txType can "credit" or "debit".
I need to get an opening and closing balance when returning transactions between two dates.



The first row of the results should be the Opening Balance, then a list of all tx between the dates and the last row to be a Closing balance



Getting the list isn't a train smash but for the balances, I currently have the following



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


this gives a very big amount than what it should be.



And for the Closing balance, I have no idea how to go about it










share|improve this question















I have a table 'transactions(txDate, amount, txType) where txType can "credit" or "debit".
I need to get an opening and closing balance when returning transactions between two dates.



The first row of the results should be the Opening Balance, then a list of all tx between the dates and the last row to be a Closing balance



Getting the list isn't a train smash but for the balances, I currently have the following



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


this gives a very big amount than what it should be.



And for the Closing balance, I have no idea how to go about it







sql sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 14:58









octano

18815




18815










asked Nov 9 at 12:53









Mxo

4511




4511







  • 4




    it would be good to include some sample data and expected result for them
    – Radim Bača
    Nov 9 at 12:55






  • 1




    What's a train smash?
    – nicomp
    Nov 9 at 12:57










  • Have you used window functions?
    – Salman A
    Nov 9 at 13:05












  • 4




    it would be good to include some sample data and expected result for them
    – Radim Bača
    Nov 9 at 12:55






  • 1




    What's a train smash?
    – nicomp
    Nov 9 at 12:57










  • Have you used window functions?
    – Salman A
    Nov 9 at 13:05







4




4




it would be good to include some sample data and expected result for them
– Radim Bača
Nov 9 at 12:55




it would be good to include some sample data and expected result for them
– Radim Bača
Nov 9 at 12:55




1




1




What's a train smash?
– nicomp
Nov 9 at 12:57




What's a train smash?
– nicomp
Nov 9 at 12:57












Have you used window functions?
– Salman A
Nov 9 at 13:05




Have you used window functions?
– Salman A
Nov 9 at 13:05












2 Answers
2






active

oldest

votes

















up vote
1
down vote













You could use CASE in 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





share|improve this answer




















  • Thanks... Works great!!
    – Mxo
    13 hours ago










  • @Mxo you are welcome :)
    – Radim Bača
    12 hours ago

















up vote
0
down vote













I think you could use SUM() OVER () window function to calculate running sum over dates:



WITH txn_data AS ( 
SELECT TransactionDate, txType, Amount
FROM dbo.Transaction
UNION ALL
SELECT @startDate, 'CF', 0
UNION ALL
SELECT @endDate, 'BAL', 0
), txn_sums AS (
SELECT
TransactionDate, txType, Amount,
SUM(IIF(txType = 'debit', -1, 1) * Amount) OVER (ORDER BY TransactionDate, CASE txType WHEN 'CF' THEN -1 WHEN 'BAL' THEN 1 ELSE 0 END) AS Balance
FROM txn_data
)
SELECT *
FROM txn_sums
WHERE TransactionDate >= @startDate AND TransactionDate < DATEADD(DAY, 1, @endDate)


Note that each row will contain the sum of all previous transactions plus the current transaction.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53226085%2fcalculating-closing-and-opening-balance-in-sql%23new-answer', 'question_page');

    );

    Post as a guest






























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote













    You could use CASE in 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





    share|improve this answer




















    • Thanks... Works great!!
      – Mxo
      13 hours ago










    • @Mxo you are welcome :)
      – Radim Bača
      12 hours ago














    up vote
    1
    down vote













    You could use CASE in 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





    share|improve this answer




















    • Thanks... Works great!!
      – Mxo
      13 hours ago










    • @Mxo you are welcome :)
      – Radim Bača
      12 hours ago












    up vote
    1
    down vote










    up vote
    1
    down vote









    You could use CASE in 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





    share|improve this answer












    You could use CASE in 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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 9 at 13:01









    Radim Bača

    7,95111025




    7,95111025











    • Thanks... Works great!!
      – Mxo
      13 hours ago










    • @Mxo you are welcome :)
      – Radim Bača
      12 hours ago
















    • Thanks... Works great!!
      – Mxo
      13 hours ago










    • @Mxo you are welcome :)
      – Radim Bača
      12 hours ago















    Thanks... Works great!!
    – Mxo
    13 hours ago




    Thanks... Works great!!
    – Mxo
    13 hours ago












    @Mxo you are welcome :)
    – Radim Bača
    12 hours ago




    @Mxo you are welcome :)
    – Radim Bača
    12 hours ago












    up vote
    0
    down vote













    I think you could use SUM() OVER () window function to calculate running sum over dates:



    WITH txn_data AS ( 
    SELECT TransactionDate, txType, Amount
    FROM dbo.Transaction
    UNION ALL
    SELECT @startDate, 'CF', 0
    UNION ALL
    SELECT @endDate, 'BAL', 0
    ), txn_sums AS (
    SELECT
    TransactionDate, txType, Amount,
    SUM(IIF(txType = 'debit', -1, 1) * Amount) OVER (ORDER BY TransactionDate, CASE txType WHEN 'CF' THEN -1 WHEN 'BAL' THEN 1 ELSE 0 END) AS Balance
    FROM txn_data
    )
    SELECT *
    FROM txn_sums
    WHERE TransactionDate >= @startDate AND TransactionDate < DATEADD(DAY, 1, @endDate)


    Note that each row will contain the sum of all previous transactions plus the current transaction.






    share|improve this answer


























      up vote
      0
      down vote













      I think you could use SUM() OVER () window function to calculate running sum over dates:



      WITH txn_data AS ( 
      SELECT TransactionDate, txType, Amount
      FROM dbo.Transaction
      UNION ALL
      SELECT @startDate, 'CF', 0
      UNION ALL
      SELECT @endDate, 'BAL', 0
      ), txn_sums AS (
      SELECT
      TransactionDate, txType, Amount,
      SUM(IIF(txType = 'debit', -1, 1) * Amount) OVER (ORDER BY TransactionDate, CASE txType WHEN 'CF' THEN -1 WHEN 'BAL' THEN 1 ELSE 0 END) AS Balance
      FROM txn_data
      )
      SELECT *
      FROM txn_sums
      WHERE TransactionDate >= @startDate AND TransactionDate < DATEADD(DAY, 1, @endDate)


      Note that each row will contain the sum of all previous transactions plus the current transaction.






      share|improve this answer
























        up vote
        0
        down vote










        up vote
        0
        down vote









        I think you could use SUM() OVER () window function to calculate running sum over dates:



        WITH txn_data AS ( 
        SELECT TransactionDate, txType, Amount
        FROM dbo.Transaction
        UNION ALL
        SELECT @startDate, 'CF', 0
        UNION ALL
        SELECT @endDate, 'BAL', 0
        ), txn_sums AS (
        SELECT
        TransactionDate, txType, Amount,
        SUM(IIF(txType = 'debit', -1, 1) * Amount) OVER (ORDER BY TransactionDate, CASE txType WHEN 'CF' THEN -1 WHEN 'BAL' THEN 1 ELSE 0 END) AS Balance
        FROM txn_data
        )
        SELECT *
        FROM txn_sums
        WHERE TransactionDate >= @startDate AND TransactionDate < DATEADD(DAY, 1, @endDate)


        Note that each row will contain the sum of all previous transactions plus the current transaction.






        share|improve this answer














        I think you could use SUM() OVER () window function to calculate running sum over dates:



        WITH txn_data AS ( 
        SELECT TransactionDate, txType, Amount
        FROM dbo.Transaction
        UNION ALL
        SELECT @startDate, 'CF', 0
        UNION ALL
        SELECT @endDate, 'BAL', 0
        ), txn_sums AS (
        SELECT
        TransactionDate, txType, Amount,
        SUM(IIF(txType = 'debit', -1, 1) * Amount) OVER (ORDER BY TransactionDate, CASE txType WHEN 'CF' THEN -1 WHEN 'BAL' THEN 1 ELSE 0 END) AS Balance
        FROM txn_data
        )
        SELECT *
        FROM txn_sums
        WHERE TransactionDate >= @startDate AND TransactionDate < DATEADD(DAY, 1, @endDate)


        Note that each row will contain the sum of all previous transactions plus the current transaction.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 9 at 13:30

























        answered Nov 9 at 13:13









        Salman A

        170k65328413




        170k65328413



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53226085%2fcalculating-closing-and-opening-balance-in-sql%23new-answer', 'question_page');

            );

            Post as a guest














































































            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo