Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Sorting an internal table

Former Member
0 Kudos

I want to sort a internal table according to fields which are in other table.

i am having a internal table populated now i want to sort this table depending upon some fields which are in second table the fields are stored in the different lines in the second table.

please help me

12 REPLIES 12

Former Member
0 Kudos

hi umesh,

SORT itab.

Extras:

1. ... BY f1 f2 ... fn

2. ... ASCENDING

3. ... DESCENDING

4. ... AS TEXT

5. ... STABLE

The syntax check performed in an ABAP Objects context is stricter than in other ABAP areas. See Field symbols not allowed as sort criterion.

Effect

The entries in the internal table are sorted in ascending order using the key from the table definition (DATA, TYPES).

Addition 1

... BY f1 f2 ... fn

Effect

Uses the sort key defined by the sub-fields f1, f2, ..., fn of the table itab instead of the table key. The fields can be of any type; even number fields and tables are allowed.

You can also specify the sort fields dynamically in the form (name). If name is blank at runtime, the sort field is ignored. If itab is a table with a header line, you can also use a field symbol pointing to the header line of itab as a dynamic sort criterion. A field symbol that is not assigned is ignored. If a field symbol is assigned, but does not point to the header line of the internal table, a runtime error occurs.

If the line type of the internal table contains object reference variables as components, or the entire line type is a reference variable, you can use the attributes of the object to which a reference is pointing in a line as sort criteria (see Attributes of Objects as the Key of an Internal Table.

You can address the entire line of an internal table as the key using the pseudocomponent TABLE_LINE. This is particularly relevant for tables with a non-structured line type when you want to address the whole line as the key of the table (see also Pseudocomponent TABLE_LINE With Internal Tables).

If you use one of the additions 2 to 5 before BY, it applies to all fields of the sort key by default. You can also specify these additions after each individual sort field f1, f2, ..., fn. For each key field, this defines an individual sort rule which overrides the default.

Addition 2

... ASCENDING

Effect

Sorts in ascending order. This is also the default if no sort order is specified directly after SORT. For this reason, it is not necessary to specify ASCENDING explicitly as the default sort order.

With the addition BY, you can also specify ASCENDING directly after a sort field to define ascending order explicitly as the sort sequence for this field.

Addition 3

... DESCENDING

Effect

Sorts in descending order. If the addition comes right after SORT, DESCENDING is taken as the default for all fields of the sort key.

With the addition BY, you can also specify DESCENDING directly after a sort field.

Addition 4

... AS TEXT

Effect

Text fields are sorted appropriate to the locale. This means that the relative order of characters is defined according to the text environment being used.

When an internal mode is opened (in other words, when a roll area is opened), the text environment is automatically set to the logon language specified in the user master record. If necessary, however, you can change the text environment explicitly in your program by using a SET-LOCALE statement.

If the addition comes directly after itab, locale-specific rules are used for all fields of the sort key where the type of these fields is C or W. After the sort, the sequence of entries usually does not match the sequence which results otherwise, without using the addition AS TEXT, i.e. with binary sorting.

With the addition BY, you can also specify AS TEXT directly after a sort field, provided it is of type C or W, or a structured type. Otherwise, a runtime error occurs. In sort fields with a structured type, AS TEXT only affects subcomponents with type C or W.

In case of an invalid character, a SYSLOG message is written, and the respective record is inserted at the end.

Note

Please keep the rules for site-specific sorting in mind.

Example

Sort a name table with different keys:

TYPES: BEGIN OF PERSON_TYPE,

NAME(10) TYPE C,

AGE TYPE I,

COUNTRY(3) TYPE C,

END OF PERSON_TYPE.

DATA: PERSON TYPE STANDARD TABLE OF PERSON_TYPE WITH

NON-UNIQUE DEFAULT KEY INITIAL SIZE 5,

WA_PERSON TYPE PERSON_TYPE.

WA_PERSON-NAME = 'Muller'. WA_PERSON-AGE = 22.

WA_PERSON-COUNTRY = 'USA'.

APPEND WA_PERSON TO PERSON.

WA_PERSON-NAME = 'Moller'. WA_PERSON-AGE = 25.

WA_PERSON-COUNTRY = 'FRG'.

APPEND WA_PERSON TO PERSON.

WA_PERSON-NAME = 'Möller'. WA_PERSON-AGE = 22.

WA_PERSON-COUNTRY = 'USA'.

APPEND WA_PERSON TO PERSON.

WA_PERSON-NAME = 'Miller'. WA_PERSON-AGE = 23.

WA_PERSON-COUNTRY = 'USA'.

APPEND WA_PERSON TO PERSON.

SORT PERSON.

Now, the sequence of the table entries is as follows:

Miller 23 USA

Moller 25 FRG

Muller 22 USA

Möller 22 USA

If, for example, you apply German sort rules where the umlaut comes directly after the letter 'o' in the sort, the data record beginning with 'Möller' would not be in the right place in this sequence. It should come second.

Provided a German-language locale is set (e.g. sorting is according to German grammatical rules, see also SET LOCALE), you can sort the names according to German rules as follows:

SORT PERSON BY NAME AS TEXT.

Now, the sequence of table entries is as follows:

Miller 23 USA

Moller 25 FRG

Möller 22 USA

Muller 22 USA

Further examples:

SORT PERSON DESCENDING BY COUNTRY AGE NAME.

Now, the sequence of table entries is as follows:

Miller 23 USA

Möller 22 USA

Muller 22 USA

Moller 25 FRG

SORT PERSON DESCENDING BY AGE ASCENDING NAME AS TEXT.

Now, the sequence of table entries is as follows:

Muller 22 USA

Möller 22 USA

Miller 23 USA

Moller 25 FRG

Addition 5

... STABLE

Effect

Uses a stable sort, that is, the relative sequence of entries that have the same sort key remains unchanged.

Unlike additions 2 to 4, you cannot use this addition directly after a sort field.

Notes

General:

The number of sort fields is restricted to 250.

The sort process is only stable if you use the STABLE addition. Otherwise, a predefined sequence of fields used to sort a list is not usually retained.

It does not make sense to use the SORT command for a SORTED TABLE. If the table type is statically declared, the system returns a syntax error if you try to SORT the table. If the table type is not statically declared (for example, because the table was passed to a FORM routine as an INDEX TABLE in a parameter), and the system can interpret the SORT statement as an empty operation, it ignores the statement. This is the case when the key in the BY clause corresponds to the beginning of the table key. Otherwise, a runtime error occurs.

To delete all duplicate entries from a sorted internal table (e.g. just after SORT), you can use the DELETE ADJACENT DUPLICATES FROM itab statement.

When using the addition AS TEXT, the sequence of entries after the sort does not usually match the sequence resulting from a binary sort, i.e. if the addition AS TEXT is not specified. The consequence of this is that after the SORT, you are not allowed to access with the READ TABLE itab ... BINARY SEARCH statement.

If you still want to access data sorted apppropriate to the locale with a binary search, you can do this by including an additional component in the table where you can explictly store the data formatted using the CONVERT TEXT ... INTO SORTABLE CODE statement. This is also recommended for performance reasons if you have to re-sort the table several times according to locale-specific criteria.

If the internal table has more than 2^19 lines or is larger than 12 MB, the system sorts it physically using an external auxiliary file. You can specify the directory in which the file should be created using the SAP profile parameter DIR_SORTTMP. By default, the system uses the SAP data directory (SAP profile parameter DIR_DATA).

Notes

Performance:

The runtime required to sort an internal table increases with the number of entries and the length of the sort key.

Sorting an internal table with 100 entries with a 50 byte key requires about 1300 msn (standardized microseconds). Using a 30-byte key, the runtime is about 950 msn.

If one of the specified sort criteria is itself an internal table, SORT may sometimes take much longer.

The runtime increases if you use a stable sort.

Physical sorting reduces the runtime required for subsequent sequential processing.

hope this helps,

do reward if it helps,

priya.

Former Member
0 Kudos

Dear Umesh,

Can you please be a little more specific on what you want to do.

Regards,

Reema.

Former Member
0 Kudos

Hello umesh,

check this link.

http://help.sap.com/saphelp_nw04/helpdata/en/fc/eb3800358411d1829f0000e829fbfe/content.htm

award some points if it helps.

regards,

keerthi.

Former Member
0 Kudos

Have a look at this code:

DATA : t_marc TYPE STANDARD TABLE OF marc WITH HEADER LINE.

DATA : l_text TYPE string .

DATA : l_text1 TYPE string .

DATA : BEGIN OF t_fields OCCURS 0,

fields(10),

END OF t_fields.

t_fields-fields = 'MATNR'.

APPEND t_fields.

t_fields-fields = 'WERKS'.

APPEND t_fields.

read table t_fields index 1.

if sy-subrc eq 0.

l_text = 'MATNR'.

endif.

read table t_fields index 1.

if sy-subrc eq 0.

l_text = 'WERKS'.

endif.

SELECT * FROM marc

INTO TABLE t_marc

UP TO 100 ROWS.

SORT t_marc BY (l_text) (l_text1).

Former Member
0 Kudos

Sorry for the previos post, small mistake in the program.

here you go.

&----


*& Report ZZSORTTRY *

*& *

&----


*& *

*& *

&----


REPORT zzsorttry .

DATA : t_marc TYPE STANDARD TABLE OF marc WITH HEADER LINE.

DATA : l_text TYPE string .

DATA : l_text1 TYPE string .

DATA : BEGIN OF t_fields OCCURS 0,

fields(10),

END OF t_fields.

t_fields-fields = 'MATNR'.

APPEND t_fields.

t_fields-fields = 'WERKS'.

APPEND t_fields.

read table t_fields index 1.

if sy-subrc eq 0.

l_text = t_fields-fields.

endif.

read table t_fields index 2.

if sy-subrc eq 0.

l_text1 = t_fields-fields.

endif.

SELECT * FROM marc

INTO TABLE t_marc

UP TO 100 ROWS.

SORT t_marc BY (l_text) (l_text1).

Former Member
0 Kudos

Hai Umesh

REPORT CHAP2301.

  • Parameter for the sort criterion, can be modified by the end user

PARAMETERS COLUMN(10) DEFAULT 'NAME'.

  • Declarations for later use

TABLES CUSTOMERS.

DATA ALL_CUSTOMERS LIKE CUSTOMERS OCCURS 100

WITH HEADER LINE.

  • Filling the internal table

SELECT * FROM CUSTOMERS INTO TABLE ALL_CUSTOMERS.

  • Dynamic sort

SORT ALL_CUSTOMERS BY (COLUMN).

  • Displaying the result

LOOP AT ALL_CUSTOMERS.

WRITE: / ALL_CUSTOMERS-ID,

ALL_CUSTOMERS-NAME,

ALL_CUSTOMERS-CITY,

ALL_CUSTOMERS-TELEPHONE.

ENDLOOP.

Thanks & regards

Sreeni

Former Member
0 Kudos

Hai Umesh

also Check it

REPORT CHAP2302.

  • Parameters for the sort criterion, can be modified by the end user

PARAMETERS: COLUMN1(10) DEFAULT 'NAME',

COLUMN2 LIKE COLUMN1 DEFAULT 'ID'.

  • Declarations for later use

TABLES CUSTOMERS.

DATA ALL_CUSTOMERS LIKE CUSTOMERS OCCURS 100

WITH HEADER LINE.

  • Filling the internal table

SELECT * FROM CUSTOMERS INTO TABLE ALL_CUSTOMERS.

  • Dynamic sort with two sort criteria

SORT ALL_CUSTOMERS BY (COLUMN1) (COLUMN2) DESCENDING.

  • Displaying the result

LOOP AT ALL_CUSTOMERS.

WRITE: / ALL_CUSTOMERS-ID,

ALL_CUSTOMERS-NAME,

ALL_CUSTOMERS-CITY,

ALL_CUSTOMERS-TELEPHONE.

ENDLOOP.

Thanks & regards

Sreeni

Former Member
0 Kudos

If you have an unknown number of sort keys, then use a stable sort in a loop.

loop at sort_table.

SORT data_table BY (sort_table-COLUMN) STABLE.

endloop.

If you have say 1 to 3 sort keys, you can do

SORT data_table BY (col_name_1) (col_name_2) (col_name_3)

If any of the variables are blank, they are ignored.

Hope this helps

Michael

Former Member
0 Kudos

Hi All ,

I am having a internal table populated say table1. now i want to sort this according to certain fields which will be there in some other table say table2.

table2 is a generalised table where user can mention many fields and the sorting fields it is also having one field as preferrence .

first i sort table2 by preferrence.

then now according to fields intable2 i want to sort the table1.

Please help

Former Member
0 Kudos

Hai

PARAMETERS: COLUMN1(10) DEFAULT 'NAME',

COLUMN2 LIKE COLUMN1 DEFAULT 'ID'.

  • Declarations for later use

TABLES CUSTOMERS.

DATA ALL_CUSTOMERS LIKE CUSTOMERS OCCURS 100

WITH HEADER LINE.

  • Filling the internal table

SELECT * FROM CUSTOMERS INTO TABLE ALL_CUSTOMERS.

  • Dynamic sort with two sort criteria

SORT ALL_CUSTOMERS BY (COLUMN1) (COLUMN2) DESCENDING.

  • Displaying the result

LOOP AT ALL_CUSTOMERS.

WRITE: / ALL_CUSTOMERS-ID,

ALL_CUSTOMERS-NAME,

ALL_CUSTOMERS-CITY,

ALL_CUSTOMERS-TELEPHONE.

ENDLOOP.

Thanks & regards

Sreeni

Former Member
0 Kudos

What is the maximum number of fields that can enter the internal table 2.

Assuming 10 fields can come.

Loop at <itab2>.

case sy-tabix.

when '1'.

l_field1 = itab2-fieldname.

when '2'.

l_field2 = itab2-fieldname.

.....till l_field10.

endloop.

Now sort <itab1> by (l_field1) (l_field2) ...(l_field10).

even if l_field3 to l_field10 has no entries, they will be ignored and you want get any dump.

Is this okay?

Former Member
0 Kudos

Hai

PARAMETERS: COLUMN1(10) DEFAULT 'NAME',

COLUMN2 LIKE COLUMN1 DEFAULT 'ID'.

  • Declarations for later use

TABLES CUSTOMERS.

DATA ALL_CUSTOMERS LIKE CUSTOMERS OCCURS 100

WITH HEADER LINE.

  • Filling the internal table

SELECT * FROM CUSTOMERS INTO TABLE ALL_CUSTOMERS.

  • Dynamic sort with two sort criteria

SORT ALL_CUSTOMERS BY (COLUMN1) (COLUMN2) DESCENDING.

  • Displaying the result

LOOP AT ALL_CUSTOMERS.

WRITE: / ALL_CUSTOMERS-ID,

ALL_CUSTOMERS-NAME,

ALL_CUSTOMERS-CITY,

ALL_CUSTOMERS-TELEPHONE.

ENDLOOP.

1. SORT itab.

2. SORT.

Variant 1

SORT itab.

Additions

1. ... DESCENDING

2. ... ASCENDING

3. ... BY f1 f2 ... fi

Effect

Sorts the entries of the internal table itab in ascending order.

The default key is used as the sort key for internal tables.

Notes

The number of sort fields is restricted to 250.

The sorting process is not stable, i.e. if no sort is performed for a predefined sequence of fields, the sequence is not retained.

To delete all duplicate entries from a sorted internal table, you can specify DELETE ADJACENT DUPLICATES FROM itab after SORT .

The sort itself uses the Quicksort process where the key fields for all the data records are retrieved and placed in an area of main memory.

If there is not enough space in memory, the key fields are written to a temporary file and sorted by an external sort program. You can modify the directory which the SORT uses to store such auxiliary files by modifying the SAP profile parameter DIR_SORTTMP . Normally, auxiliary files are created in the SAP data directory (SAP profile parameter DIR_DATA ).

Addition 1

... DESCENDING

Effect

Sorts itab in descending order.

Addition 2

... ASCENDING

Effect

Sorts itab in ascending order (default).

Addition 3

... BY f1 f2 ... fi

Effect

Sorts itab by the sub-fields f1 , f2 , ..., fi which form the sort key. These fields can be any type (even number fields or tables). Unless you specify otherwise, the sort is in ascending order. You can also use additions 1 and 2 before BY if you want all sub-fields to apply. To change the sort sequence for each individual field, specify DESCENDING or ASCENDING after each of the sub-fields f1 , f2 , ..., fi .

Example

DATA: BEGIN OF PEOPLE OCCURS 5,

NAME(10),

AGE TYPE I,

NATIONALITY(3),

END OF PEOPLE.

PEOPLE-NAME = 'Sally'. PEOPLE-AGE = 22.

PEOPLE-NATIONALITY = 'USA'. APPEND PEOPLE.

PEOPLE-NAME = 'Peter'. PEOPLE-AGE = 25.

PEOPLE-NATIONALITY = 'FRG'. APPEND PEOPLE.

PEOPLE-NAME = 'Paula'. PEOPLE-AGE = 22.

PEOPLE-NATIONALITY = 'USA'. APPEND PEOPLE.

PEOPLE-NAME = 'Peter'. PEOPLE-AGE = 23.

PEOPLE-NATIONALITY = 'USA'. APPEND PEOPLE.

SORT PEOPLE.

The sequence of table entries now reads: 'Paula' , 'Peter' from 'FRG' , 'Peter' from 'USA' , 'Sally' .

SORT PEOPLE DESCENDING BY NATIONALITY AGE NAME.

The sequence now reads: 'Peter' from 'USA' , 'Sally' , 'Paula' , 'Peter' from 'FRG' .

SORT PEOPLE DESCENDING BY AGE ASCENDING NAME.

The sequence now reads: 'Sally' , 'Paula' , 'Peter' from 'USA' , 'Peter' from 'FRG' .

Notes

If a sort criterion is not known until runtime, you can use SORT itab BY ... (name) ... to specify it dynamically as the contents of the field name . If name is blank at runtime, the sort criterion is ignored. If name contains an invalid component name, a runtime error occurs.

You can use offset and length specifications to further restrict sort criteria, regardless of whether they are specified statically or dynamically.

If itab is an internal table with a header line, you can also use a field symbol pointing to the header line of itab as a dynamic sort criterion. If the field symbol does not point to the header line of the internal table, a runtime error occurs.

Note

Performance

The runtime required to sort an internal table increases with the number of entries and the width of the sort key.

Sorting an internal table with 100 entries and the 50-byte wide default key would take about 1300 msn (standardized microseconds). A 30-byte wide sort key would need about 950 msn.

If one of the specified sort criteria is itself an internal table, the SORT may sometimes take longer.

Runtime errors

SORT_ITAB_FIELD_INVALID :A field symbol used as a dynamic sort criterion does not point to the header line of the internal table to be sorted.

SORT_TOO_MANY_FIELDS : More than 250 sort criteria.

Related APPEND ... SORTED BY

Variant 2

SORT.

Additions

1. ... DESCENDING (similar to variant 1)

2. ... ASCENDING (similar to variant 1)

3. ... BY f1 f2 ... fi

4. ... BY fg

Effect

Sorts the dataset generated with EXTRACT by the fields in the field group HEADER (see FIELD-GROUPS ).

Here, blank fields (i.e. fields not defined with EXTRACT ) are inserted before all non-blank fields, regardless of whether the sort sequence is in ascending or descending order.

Notes

The number of sort criteria is restricted to 50.

As with variant 1, any sequence of fields you specify for sorting purposes does not remain fixed. Any sequence of records which belongs to different field groups, but has the same HEADER field contents, is arbitrary.

Again like variant 1, sorting takes place in main memory if at all possible. If there is insufficient space there, ABAP/4 calls an external sort program. You can modify the directory used to create the temporary auxiliary file by modifying the SAP profile parameter DIR_SORTTMP .

As soon as a dataset has been processed with SORT or LOOP ... ENDLOOP , you cannot extract any more records with EXTRACT .

Addition 3

... BY f1 f2 ... fi

Effect

Can sort only by fields in the field group HEADER .

Otherwise, the effect is similar to variant 1.

Addition 4

... BY fg

Effect

Sorts by the fields in field group fg .

However, the only fields which can be sorted are those in the field group HEADER , i.e. the field group fg can consist only of fields from the field group HEADER (see INSERT ... INTO ).

Example

DATA: ONR(7), DATE TYPE D, POSITION(3) TYPE N,

CUSTOMER(16),

PNR(5) TYPE N, NAME(10), UNITS TYPE I,

ORDERS TYPE I.

FIELD-GROUPS: HEADER, ORDER, PRODUCT, DATE_FIRST.

INSERT ONR DATE POSITION INTO HEADER.

INSERT CUSTOMER INTO ORDER.

INSERT PNR NAME UNITS INTO PRODUCT.

INSERT DATE ONR POSITION INTO DATE_FIRST.

ONR = 'GF00012'. DATE = '19921224'.

POSITION = '000'. CUSTOMER = 'Good friend (2.)'.

EXTRACT ORDER.

ADD 1 TO POSITION.

PNR = '12345'. NAME = 'Screw'. UNITS = 100.

EXTRACT PRODUCT.

ADD 1 TO POSITION.

PNR = '23456'. NAME = 'Nail'. UNITS = 200.

EXTRACT PRODUCT.

ONR = 'MM00034'. DATE = '19920401'.

POSITION = '000'. CUSTOMER = 'Moneymaker'.

EXTRACT ORDER.

ADD 1 TO POSITION.

PNR = '23456'. NAME = 'Nail'. UNITS = 300.

EXTRACT PRODUCT.

ADD 1 TO POSITION.

PNR = '34567'. NAME = 'Hammer'. UNITS = 4.

EXTRACT PRODUCT.

ONR = 'GF00011'. DATE = '19921224'.

POSITION = '000'. CUSTOMER = 'Good friend (1.)'.

EXTRACT ORDER.

ADD 1 TO POSITION.

PNR = '34567'. NAME = 'Hammer'. UNITS = 5.

EXTRACT PRODUCT.

SORT BY DATE_FIRST.

LOOP.

AT ORDER.

WRITE: /, / DATE, ONR, POSITION,

CUSTOMER, 'ordered:'.

ENDAT.

AT PRODUCT.

WRITE: / DATE, ONR, POSITION,

PNR, NAME, UNITS.

ENDAT.

ENDLOOP.

This generates the following output:

01041992 MM00034 000 Moneymaker ordered:

01041992 MM00034 001 23456 Nail 300

01041992 MM00034 002 34567 Hammer 4

24121992 GF00011 000 Good friend (1.) ordered:

24121992 GF00011 001 34567 Hammer 5

24121992 GF00012 000 Good friend (2.) ordered:

24121992 GF00012 001 12345 Screw 100

24121992 GF00012 002 23456 Nail 200

Note

Performance

The runtime required to sort an internal table increases with the number of entries and the width of the sort key.

Note

Runtime errors

SORT_EXTRACT_TOO_MANY_FIELDS : More than 50 sort criteria

SORT_FIELD_NOT_IN_HEADER : Sort criterion not in field group HEADER

SORT_NO_HEADER : Field group HEADER not created

SORT_WITHIN_LOOP : SORT on extract dataset within LOOP on extract dataset

Thanks & regards

Sreeni