Re: Averaging Numbers

From: Date: Wed, 15 Aug 2001 17:20:52 +0000
Subject: Re: Averaging Numbers
References: 1  Groups: php.db 
Request: Send a blank email to php-db+get-11388@lists.php.net to get a copy of this message
"Jeff Oien" <jeff@webdesigns1.com> wrote in message news:PGEBKOPJJHHICHGDKCCIKECIDAAA.jeff@webdesigns1.com... > I'm having a hard time learning how to get an average. I have a database > that gets a number and inserts in into a MySQL database every 1/2 hour > during the day. For the current half hour, I want to get the last 15 days > numbers for the same time as the time it is now. I can retrieve and display > the numbers fine, I just don't know how to go about putting these all into > variables or an array or if I can do this within a query and then take an > average for them. First, a modified 'do-it-in-PHP' solution to return the average of an arbitrary number of results: <?php $result = mysql_query($query); $num = mysql_num_rows($result); $sum = 0; while ($row = mysql_fetch_array($result)) $sum += $row["val"]; $avg = $sum/$num; ?> And two variants on 'do-it-in-SQL- and-just-get-the-answer': SELECT AVG(val) FROM table WHERE halfhour = $nowAsHalfHour ORDER BY date DESC LIMIT 15 or, alternatively, SELECT AVG(val) FROM table WHERE halfhour = $nowAsHalfHour AND date > $nowMinus15Days ;-)

« previous php.db (#11388) next »