patternphpMinor
Average of averages
Viewed 0 times
averagesaveragestackoverflow
Problem
I need to get the average of multiple averages calculated basing on data contained on a sql database.
To do that, I'm using this code:
But I believe this is not the best way to do this.
How can I make my code cleaner?
To do that, I'm using this code:
$a = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediaa FROM values WHERE type ='a'"));
$b = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediab FROM values WHERE type ='b'"));
$c = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediac FROM values WHERE type ='c'"));
$d = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediad FROM values WHERE type ='d'"));
$e = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediae FROM values WHERE type ='e'"));
$f = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediaf FROM values WHERE type ='f'"));
$g = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediag FROM values WHERE type ='g'"));
$h = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediah FROM values WHERE type ='h'"));
$i = mysqli_fetch_assoc(mysqli_query($connessione,"SELECT AVG(voto) AS mediai FROM values WHERE type ='i'"));
$sum = $a['mediaa']+$b['mediab']+$c['mediac']+$d['mediad']+$e['mediae']+$f['mediaf']+$g['mediag']+$h['mediah']+$i['mediai'];
$globalavg = ($sum/9)*10;
echo 'Global average: ';
echo $globalavg;But I believe this is not the best way to do this.
How can I make my code cleaner?
Solution
Let the database do the hard work for you. Instead of selecting the values individually and summing them yourself, you can union your queries and sum the results in sql:
Assuming you put this query in a
Not only the PHP is simpler, it's more efficient to run one query than 9.
SELECT SUM(x) / 9 * 10 AS globalavg FROM (
SELECT AVG(voto) AS x FROM values WHERE type ='a'
UNION ALL
SELECT AVG(voto) AS x FROM values WHERE type ='b'
UNION ALL
SELECT AVG(voto) AS x FROM values WHERE type ='c'
UNION ALL
-- follow the pattern for d, e, f, ...
) tAssuming you put this query in a
$query variable in PHP, your code can be simplified as:$result = mysqli_fetch_assoc(mysqli_query($connessione, $query));
$globalavg = $result['globalavg'];
echo 'Global average: ';
echo $globalavg;Not only the PHP is simpler, it's more efficient to run one query than 9.
Code Snippets
SELECT SUM(x) / 9 * 10 AS globalavg FROM (
SELECT AVG(voto) AS x FROM values WHERE type ='a'
UNION ALL
SELECT AVG(voto) AS x FROM values WHERE type ='b'
UNION ALL
SELECT AVG(voto) AS x FROM values WHERE type ='c'
UNION ALL
-- follow the pattern for d, e, f, ...
) t$result = mysqli_fetch_assoc(mysqli_query($connessione, $query));
$globalavg = $result['globalavg'];
echo 'Global average: ';
echo $globalavg;Context
StackExchange Code Review Q#62623, answer score: 5
Revisions (0)
No revisions yet.