Skip to Content

Summing the Balances together

Hi guys,

I have this query that gets the outstanding balances per business partner (customers) and orders them in descending. Where I'm stuck is how to sum all these balances together to give me one total value at the end. The following is the query:

SELECT T0.[CardName], case when T0.[Currency]   = 'USD' THEN  T0.[BalanceFC] else  T0.[BalanceSys] end AS 'Balance' FROM OCRD T0
 WHERE T0.[CardType] ='C' and T0.[BalanceSys] >'0' and T0.[BalanceFC] >'0' ORDER BY  T0.[BalanceSys] DESC

I tried to use SUM() but it just copies the values to a new field and doesn't give me what I'm expecting.

Any help will much be appreciated. Thanks.

- Macdonald

Add a comment
10|10000 characters needed characters exceeded

Assigned Tags

Related questions

2 Answers

  • Best Answer
    Posted on Aug 17, 2016 at 08:14 AM

    Hi Macdonald,

    A couple of things:

    • Why are you using the case statement? Why not always use T0.[BalanceSys], or is the system currency not USD? With the case statement you are showing one of two possible fields, but then in the ORDER BY clause, you order it specifically by the T0.[BalanceSys] field.
    • You could use a simple UNION ALL:
      SELECT T0.[CardName]
      , case
      when T0.[Currency] = 'USD' THEN T0.[BalanceFC]
      else T0.[BalanceSys]
      end AS 'Balance'
      FROM OCRD T0
      WHERE T0.[CardType] ='C' and T0.[BalanceSys] >'0' and T0.[BalanceFC] >'0'
      UNION ALL
      SELECT 'Total'
      , SUM(case
      when T0.[Currency] = 'USD' THEN T0.[BalanceFC]
      else T0.[BalanceSys]
      end) AS 'Balance'
      FROM OCRD T0
      WHERE T0.[CardType] ='C' and T0.[BalanceSys] >'0' and T0.[BalanceFC] >'0'
      ORDER BY Balance DESC
      However, because you are ordering in descending order, the total would always be the first row as it is the largest value.


    Regards,

    Johan

    Add a comment
    10|10000 characters needed characters exceeded

  • Posted on Aug 17, 2016 at 10:01 AM

    Thank you very much, I can work with this.

    Add a comment
    10|10000 characters needed characters exceeded

Before answering

You should only submit an answer when you are proposing a solution to the poster's problem. If you want the poster to clarify the question or provide more information, please leave a comment instead, requesting additional details. When answering, please include specifics, such as step-by-step instructions, context for the solution, and links to useful resources. Also, please make sure that you answer complies with our Rules of Engagement.
You must be Logged in to submit an answer.

Up to 10 attachments (including images) can be used with a maximum of 1.0 MB each and 10.5 MB total.