Q:

How to count number of records of a field in internal table in select statment?

I took a internal table of type ty_marc.
in this internal table i took 2 fields matnr and werks_d.
I want to count number of materials manufactured in the plant (marc-werks) based on the entry given by user.
I wrote the code as...
if so_matnr is not initial.
select matnr werks from marc 
into table it_marc
where matnr in so_matnr.
endif.

loop at it_marc into w_marc.
write :/ w_marc-matnr. ( how to count total number of material eg:- material number : 100-100 to 100-110).
       w_marc-werks.
endloop.

I want to count total number of material and display the count in another field of same internal table.
Note : there could be 10 material for material number 100-100, so i want the count as 10 in another field of same internal table and 100-110 could have n records and the count should be n in the field.

A:

There are two easy options.
If you don't actually care about the plant (werks), use the group by clause and the count function in your select statement. Something like:
select matnr, count(*)
from marc
where matnr in so_matnr
group by matnr
into table it_marc_count.

Structure it_marc_count would need to have an integer field in the second position (and matnr in the first obviously).
If you do need werks, the easiest is to sort it_marc by matnr then use the at end and sum constructs in the loop at loop (or something similar). The examples at the end of Processing Table Entries in Loops should get you started.

