Application Development and Automation 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: 
Read only

Count in internal table

Former Member
0 Likes
1,390

Hi,

How can i get the number of records(count) in an Internal table based on some condition.

6 REPLIES 6
Read only

jayanthi_jayaraman
Active Contributor
0 Likes
706

Hi,

data cnt type i.

i = 0.

Loop at internaltable into workarea where condition.

i = i + 1.

endloop.

write : 'Count:',i.

Read only

Former Member
0 Likes
706

Hi,

Loop at itab where <cond>.

<b>add 1 to counter</b>.

endloop.

Also,If u r doing a looping alone then, After looping at the internal table (after endloop) u can also get the value of <b>sy-index</b>. This will hold the count in that internal table.

http://www.sapdevelopment.co.uk/reporting/ind/ind_count.htm

Thanks & Regards,

Judith.

Message was edited by: Judith Jessie Selvi

Read only

0 Likes
706

Hi Judith,

I am not sure that is correct. SY-INDEX will hold the index of the last record that was looped at, but this may not necessarily be equal to the number of records matching the condition. (By the way, possibly you mean SY-TABIX).

Consider the following example. After looping through the table, SY-TABIX = 3. There are, however, only 2 records matching the condition.

data: begin of itab occurs 0,

val1 type c,

val2 type c,

end of itab.

itab-val1 = 'A'.

itab-val2 = 'C'.

append itab.

itab-val1 = 'A'.

itab-val2 = 'B'.

append itab.

itab-val1 = 'A'.

itab-val2 = 'C'.

append itab.

loop at itab where val2 = 'C'.

endloop.

write: sy-tabix.

Read only

Former Member
0 Likes
706

Hi Suzane,

You cannot find the count in one direct statement. You will have to use the count() in your select, or if that is not possible, then:

Easy option:

loop at itab where field1 = condition1.

counter = counter + 1.

endloop.

A lesser easy way, and not always feasible:

itab_copy[] = itab[].

delete itab_copy where field1 NE condition1.

describe table itab_copy lines lv_lines.

Cheers, Rahul

Read only

Former Member
0 Likes
706

I think the only possible way is by looping over the table:

Counter = 0.

LOOP AT itab WHERE cond1 AND cond2.

Counter = counter + 1.

Endloop.

You might gain some speed if it is a large table by

using field symbols or references, this avoids the cost of copying the table record to the work area.

Loop at itab assigning <FS> where cond1 AND cond2.

counter = counter + 1.

endloop.

or

Loop at itab reference into dref where cond1 AND cond2.

counter = counter + 1.

endloop.

Hope this helps.

Joris.

Read only

Former Member
0 Likes
706

Data: v_line type i.

Describe table itab lines v_line. (for all records)

Write: v_line.

loop at itab.

if (condition)

add 1 to v_line.

endif.

endloop.