More about Totalling
There are many other ways to use the SUM clause to produce totals. As well as totalling from one group to another, you may form totals within the same group. Here's how you might enhance our four-yearly table with row and column totals. (Absorb this example slowly.)
Report writer totals repeating values automatically along the horizontal or vertical axes. Notice that you should not place any subscripts after the data-name that is the operand of the SUM clause.
A SUM may be combined in an entry with a multiple COLUMN (or LINE) clause to give you a series of totals of another repeating entry with the same number of repetitions, as you see in the last line of this example:
The total line may also be in a different group from the repeating line. If so, you might then remove the OCCURS 12 on the first LINE entry and GENERATE the group containing it 12 times.
As well as totalling a field using SUM, you may count the occurrences using the COUNT clause. COUNT simply adds 1 each time instead of the value of the field. You may COUNT the number of times any REPORT SECTION item appears, including LINEs or whole groups. All multiple occurrences contribute to the COUNT.
You may use SUM and COUNT as terms of a SOURCE expression. Be sure to enclose each term in parentheses. For example, to find the average amount of the subscription of our four sports above, you may write:
(As usual, the words SOURCE IS are optional.) If the divisor (the COUNT term above) happens to be zero, report writer will detect the error, unless you write OVERFLOW PROCEDURE IS OMITTED in your RD statement. The action taken depends on what, if anything, you coded in the OVERFLOW PROCEDURE clause. (By default, report writer will detect the error and write an error message on your terminal or job log, leaving the field blank.)
You may also total numeric fields directly from other sections in your DATA DIVISION. (With the older ANS COBOL-IT Report Writer this method was necessary to obtain totals. You coded the name of the FILE, WORKING-STORAGE, or LINKAGE SECTION item as an operand of the SUM clause in the lowest-level CONTROL FOOTING.) With such external items, you may use subscripts, and you may also SUM an arithmetic expression; for instance:
If the item does not already appear as a SOURCE, this is the only method of totalling it. So this technique is useful where you require totals of a field but do not want to show the individual values that were added to produce the total. Its main disadvantage is that it may not be clear to the reader of your program exactly when the values are added into the total. See the remainder of this publication for a discussion of the relevant rules.