Xbasic

DBSUM Function

Syntax

Sum_Of_Values as N = DBSUM(Lookup_Table as C, tagname as C, Key_Value as A, Lookup_Expression as C)

Arguments

Lookup_TableCharacter

The full drive, path, name, and extension of the table. If you omit the drive, path, and extension, Alpha Anywhere searches the directory of the current table.

tagname

The name of an index.

Key_Value

An explicit value or the name of a field in the table containing a value.

Lookup_ExpressionCharacter

An expression based on numeric or exponent numeric field(s) in the Lookup_Table.

Returns

Sum_Of_ValuesNumeric

Returns the total sum of the specified fields in the table. Returns 0 if no records are found.

Description

Returns the sum of fields of matching records in a specified table.

Discussion

DBSUM() searches the specified Lookup_Table for one or more records with the specified Key_Value, and returns the sum of the values contained in Lookup_Expression. If no records with matching key values are found, DBSUM() returns a zero value.

Example 

Assume that a customer order table (ORDER) contains the following records:

CUSTOMER_ID

AMOUNT

C100

234.45

C100

123.67

C100

100.23

C101

231.34

C102

111.12

C102

987.23

The following expression returns the sum of the values in the AMOUNT field for all the records in the ORDER table with a customer Id number of "C102":

? dbsum("ORDER.DBF", "CUST_ID", "C102", "AMOUNT")
= 1098.35

This example uses the Customer_ID index to find the sum of the discounts on items sold to customer ID "00000005".

? dbsum("invoice_header", "Customer_ID", "00000005", "Discount")
= 10

This example is based on the invoice_items table of the AlphaSports database.

dim pnum as C = "P001"
? dbsum("invoice_items", "Product_ID", pnum, "Quantity")
= 18

Example: Filtering Results 

The Lookup_Expression can be used to filter the records. For example, the following Xbasic queries the AlphaSports product table to sum products with a retail greater than $10 for a particular vendor:

dim vnum as C = "V002"
? dbsum("product", "vendor", vnum, "if(retail > 10,Qty_In_Sto,0)")
= 2138

See Also