Hello folks,
What is the best way to compare records of an internal table based on a single column values?
Say, I have an internal table with values as below:
A B C 1001 10 1001 20 X 1001 30My requirement is to check if the column C contains identical values or not. In case of blank, all records should hold blank value in column C; in case 'X, all records should hold 'X'.
Kindly suggest the best approach to achieve this.
Thanks,
Rics
And what should happen if you have 2 blank fields and 2 with value 'X'?
Hi Rics,
1. Copy the internal table to another internal table it_tab2[] = it_tab1[].
2. Read the first record of it_tab1[].
Read table it_tab1 into wa_tab1 index 1.
3. Then, delete it_tab2[] with following condition,
Delete it_tab2 where c = wa_tab1-c.
4. If all the records of it_tab2 is deleted, then C field has identical values. If it_tab2 is not completed deleted then C field has values which are not identical
To check if there is only one given value in a column of an internal table, you can do the following:
READ TABLE itab WITH KEY c = 'X' TRANSPORTING NO FIELDS.
DATA(subrc1) = sy-subrc.
LOOP AT itab TRANSPORTING NO FIELDS WHERE c <> 'X'.
EXIT.
ENDLOOP.
DATA(subrc2) = sy-subrc.
IF subrc1 = 0 AND subrc2 <> 0.
"only X
ENDIF.
If you can assert that you have exactly two values as in your scenario above, you can do it as follows:
READ TABLE itab WITH KEY c = 'X' TRANSPORTING NO FIELDS.
DATA(subrc1) = sy-subrc.
READ TABLE itab WITH KEY c = ' ' TRANSPORTING NO FIELDS.
DATA(subrc2) = sy-subrc.
IF subrc1 = 0 AND subrc2 <> 0.
"only X
ELSEIF subrc1 <> 0 AND subrc2 = 0.
"only space
ELSE.
"both
ENDIF.
Or in a modern way (elegant, but in fact too much read accesses ...):
IF line_exists( itab[ c = 'X' ] ) AND
NOT line_exists( itab[ c = ' ' ).
"only X
ELSEIF NOT line_exists( itab[ c = 'X' ] ) AND
line_exists( itab[ c = ' ' ] ).
"only space
ELSE.
"both
ENDIF.
In case that there are more values possible than 'X' and ' ', see my answer above.
Probably just a SORT using COMPARE BY.
Hi All,
Thank you for your quick responses, which were all very helpful.
My problem has been solved with @Horst Keller solution. Thank you for your time and patience. 😊
Regards,
Rics
Add a comment