Gossamer Forum
Home : Products : DBMan : Customization :

Average only fields with Data

Quote Reply
Average only fields with Data
I am using the Average Mod and it works perfectly. However, I need it to average based only on fields that contain data.

Here's the code I am currently using
##################################################################
# Get the "average" value of a field.
##################################################################
sub get_average {
my $which_field = shift;
my $avg_count = 0; # Initialise the counter
my $avg_total = 0; # Initialise the total
open (DB, "<$db_file_name") or &cgierr("Unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
@lines = <DB>;
close DB;
foreach $line (@lines) {
chomp ($line);
@tmp_record = split (/\Q$db_delim\E/o, $line);
$avg_count++; # Count up each record
$avg_total = $avg_total + $tmp_record[$which_field]; # Add value to total
}
if ($avg_count > 0) {
$avg_total = int $avg_total / $avg_count; # Average the total by number of records
} else { $avg_total = 'No matches for your ID found'; }
print $avg_total;
}

Any help here greatly appreciated.
Quote Reply
Re: [bbooker] Average only fields with Data In reply to
just test for value before you count i think:

@tmp_record = split (/\Q$db_delim\E/o, $line);
if ($tmp_record[$which_field]) {
$avg_count++; # Count up each record
$avg_total = $avg_total + $tmp_record[$which_field]; # Add value to total
}
}
if ($avg_count > 0) {
$avg_total = int $avg_total / $avg_count; # Average the total by number of records
} else { $avg_total = 'No matches for your ID found'; }
print $avg_total;
}


In Reply To:
I am using the Average Mod and it works perfectly. However, I need it to average based only on fields that contain data.

Here's the code I am currently using
##################################################################
# Get the "average" value of a field.
##################################################################
sub get_average {
my $which_field = shift;
my $avg_count = 0; # Initialise the counter
my $avg_total = 0; # Initialise the total
open (DB, "<$db_file_name") or &cgierr("Unable to open db file: $db_file_name.\nReason: $!");
if ($db_use_flock) { flock(DB, 1); }
@lines = <DB>;
close DB;
foreach $line (@lines) {
chomp ($line);
@tmp_record = split (/\Q$db_delim\E/o, $line);
$avg_count++; # Count up each record
$avg_total = $avg_total + $tmp_record[$which_field]; # Add value to total
}
if ($avg_count > 0) {
$avg_total = int $avg_total / $avg_count; # Average the total by number of records
} else { $avg_total = 'No matches for your ID found'; }
print $avg_total;
}

Any help here greatly appreciated.