KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Summing up a Field
PRODUCT: 4D | VERSION: 16 | PLATFORM: Mac & Win
Published On: January 25, 2018

Often times it is necessary to add up all the values in a field, for example when building an invoicing application and pulling out the total sales for a particular customer throughout a period of time.

One way that this can be done is by creating an array, pulling the values from the table into the array, and then summing up the values in the array by stepping through it, for example:

ARRAY REAL($sale_values;0)
C_REAL($total)

Begin SQL
   SELECT sale_amt FROM Sales_Table INTO :$sale_values
End SQL

For ($i;1;Size of array($sale_values))
   $total:=$total+$sale_values{$i}
End For

While this is a straightforward way to get the sum, with the 4D command Sum this can be accomplished without having to step through an array, for example:

ARRAY REAL($sale_values;0)
C_REAL($total)

Begin SQL
   SELECT sale_amt FROM Sales_Table INTO :$sale_values
End SQL

$total:=Sum($sale_values)

An even easier way to do this, without the need for the array at all, is to just use the Sum command on the field itself, for example:

C_REAL($total)

ALL RECORDS([Sales_Table])

$total:=Sum([Sales_Table]sale_amt)

Other commands such as Min, Max, and Average can also be handled in a similar manner.