Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Table Math Question 4

Status
Not open for further replies.

NewToProgramming

Technical User
Jun 24, 2003
31
US
I have a number field in my paradox table, and I would like to average the value of all the records for that field. I was able to do a query to get the values of all the records for that field, but just don't know how to average them.
Thank you,
Mark
 
You could run a loop that will do it. You need to know the number of records read. Assuming that your values are stored in an array you could use something like:
Code:
...
var
  your_record_count, counter: Integer;
  total: Single;
  average: Single;
  record_values: Array of Single;
begin
...
SetLength(record_values, your_record_count);
total := 0;
for counter := 0 to your_record_count - 1 do
  total := total + record_values[counter];
average := total / your_record_count;
...
end;

You could amend the record_values bit to take the values straight from your query - but, unfortunately, I'm not too familiar with using the database side of Delphi.

Hope this helps!

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
Well.. One simple way would be to count the number of records - then divide it by the total in that field.

This would give you an average for that set of records anyway. For example..

The SQL statements could look like this.. to get number of records:

SELECT COUNT(afield) as RR from atable;

Then.. to get total :

SELECT SUM(afield) from atable;

In your code something like...

var
total,c,s : real;
begin
c := IBQuery1.Fields[0].asInteger;
s := IBQuery2.Fields[0].asInteger;

total := s/c;

Showmessage(floatToStr(total));

Note I have used Interbase query components here.. but pronciple is the same.


Opp.


 
eeasier again...
use this SQL statement

SELECT AVG(myField) AS average
FROM MyTable;

thats it;)
jb
 
Opp you should use the double field instead of real starting from Delphi 4, the real is still there for backward compatibility, could be changing in the next versions

Steven van Els
SAvanEls@cq-link.sr
 
Thank you, Never thought of doing an SQL for that. I had to learn some more about SQL statements, but I got it to work. Isn't the internet great?
You guys are great too.
Thanks
Mark
 
Seeing as Oppenheimer and/or jbpelletier pointed you in the right direction maybe you should reward one or both of them with a star?

Clive [infinity]
Ex nihilo, nihil fit (Out of nothing, nothing comes)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top