Calculating Numbers and Totals

When you read a sorted extract dataset using LOOP, you can access two automatically-generated fields CNT(<f>) and SUM(<g>). These fields contain the number of different values and the sums of the numeric fields respectively. The system fills these fields at the end of a control level and after reading the last record of the dataset as follows:

• CNT(<f>)

If <f> is a non-numeric field of the HEADER field group and the system sorted the extract dataset by <f>, CNT(<f>) contains the number of different values <f> assumed within the control level or entire dataset respectively.

• SUM(<g>)

If <g> is a numeric field of the extract dataset, SUM (<g>) contains the total of the values of <g> within the control level or entire dataset respectively.

You can access these fields either within the processing blocks following AT END OF or in the processing block following AT LAST, after reading the entire dataset. If you try to access the fields CNT(<f>) and SUM(<g>) without first sorting the dataset, a runtime error may occur.

REPORT DEMO.

DATA: T1(4), T2 TYPE I.

T1 ='AABB'. T2 = 1. EXTRACT TEST.
T1 ='BBCC'. T2 = 2. EXTRACT TEST.
T1 ='AAAA'. T2 = 2. EXTRACT TEST.
T1 ='AABB'. T2 = 1. EXTRACT TEST.
T1 ='BBBB'. T2 = 2. EXTRACT TEST.
T1 ='BBCC'. T2 = 2. EXTRACT TEST.
T1 ='AAAA'. T2 = 1. EXTRACT TEST.
T1 ='BBBB'. T2 = 1. EXTRACT TEST.
T1 ='AAAA'. T2 = 3. EXTRACT TEST.
T1 ='AABB'. T2 = 1. EXTRACT TEST.

SORT BY T1 T2.

LOOP.

WRITE: /20 T1, T2.

AT END OF T2.
ULINE.
WRITE: 'Sum:', 20 SUM(T2).
ULINE.
ENDAT.

AT END OF T1.
WRITE: 'Different values:', (6) CNT(T1).
ULINE.
ENDAT.

AT LAST.
ULINE.
WRITE: 'Sum:', 20 SUM(T2),
/ 'Different values:', (6) CNT(T1).
ENDAT.

ENDLOOP.

This program creates a sample extract, containing the fields of the HEADER field group only. After sorting, the system outputs the contents of the dataset, the number of the different T1 fields, and the totals of the T2 fields at the end of each control level and at the end of the loop: