Additional Blogs by SAP
cancel
Showing results for 
Search instead for 
Did you mean: 
0 Kudos

Hello World !

For my first post on SDN I have chosen a simple topic.

Throughout the years I have often heard from co-workers that one cannot trust the AT NEW/END statements to create sub-totals in ABAP reports. I have come across many programs where the developer coded the AT NEW/END statements on his own using multiple variables just because it “did not work”.

One condition for correct results is to sort the driving internal table by the fields used to create the sub-totals. That is done in most of the cases but still the results are wrong. Let’s check the following example:

  data: begin of t_test occurs 0,

    field1(10) type c,

    field2(10) type c,

    field3(10) type c.

  data: end of t_test.

 

  t_test-field1 = 'ABAP'.

  t_test-field2 = 'Programming'.

  t_test-field3 = 'Language'.

  append t_test.

 

  t_test-field1 = 'C'.

  t_test-field2 = 'Programming'.

  t_test-field3 = 'Language'.

  append t_test.

 

  sort t_test by field3.

 

  loop at t_test.

    at new field3.

      write:/ 'Field 3 - new value: ', t_test-field3.

    endat.

  endloop.

 

This is the output:

 

Field 3 - new value:  Language

Field 3 - new value:  Language

 

Although there is no new occurrence in field field3, the AT NEW statement is triggered. What went wrong ? See the following slightly modified example:

 

  data: begin of t_test2 occurs 0,

    field3(10) type c,

    field2(10) type c,

    field1(10) type c.

  data: end of t_test2.

 

  t_test2-field1 = 'ABAP'.

  t_test2-field2 = 'Programming'.

  t_test2-field3 = 'Language'.

  append t_test2.

 

  t_test2-field1 = 'C'.

  t_test2-field2 = 'Programming'.

  t_test2-field3 = 'Language'.

  append t_test2.

  sort t_test2 by field3.

  loop at t_test2.

    at new field3.

      write:/ 'Field 3 - new value: ', t_test2-field3.

    endat.

  endloop.

 

This is the output:

Field 3 - new value:  Language

This time the results are correct. Since there is only one value in field field3, the code inside the AT NEW structure is triggered only once. The difference is the order of the fields in the internal table. They should be declared in the same sequence of the desired subtotals. Summarizing: the correct functioning of AT NEW/AT END depends on:

-         Sorting the internal table by the fields to be totalized;

-         Declare the internal table with those fields at the beginning and in the order of the subtotals.

Sometimes you want to let the end-user choose the fields to be totalized. For that the best option is the ALV Grid. Still, you can achieve that by using a large string field in the beginning of the internal table, which you fill by concatenating the fields in the order chosen by the user.

7 Comments