1

I want to calculate the Average value of all other columns grouping them by collegename. i.e RVCE with Average of all other columns, BMS with Average of all other columns and so on and display the value in HTML.

SQL Database Structure Image

I have tried the following code in but it is returning me no values.

<?php
$hostname="localhost:8889";
$username="root";
$password="root";
$db = "rank";
$dbh = new PDO("MySQL:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT collegename,AVG(campus)  
FROM college       
GROUP BY collegename') as $row) {
echo "<tr>";
echo "<td>" . $row['AVG(campus)'] . "</td>";
echo "</tr>";
}
?>

2 Answers2

1

Try this one?

<?php
$hostname="127.0.0.1";
$port=8889;
$username="root";
$password="root";
$db = "rank";
$dbh = new PDO("mysql:dbname=$db;host=$hostname;port=$port", $username, $password);
foreach($dbh->query('SELECT collegename,AVG(campus) AS avg_campus  
FROM college       
GROUP BY collegename') as $row) {
echo "<tr>";
echo "<td>" . $row['collegename'] . " AVG: " . $row['avg_campus'] . "</td>";
echo "</tr>";
}
?>
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49
0
SELECT
     AVG((campus + location + cost + internet + safety + placement + hapiness + weather + fun + fests)/10) as avg_campus,
   FROM
     college
   GROUP BY
     collegename

If you have only one row for a college name, then the group by is useless and... the AVG() as well

For average of each individual column :

SELECT AVG(campus) as campus, AVG(location) as location, AVG(cost) as cost, AVG(internet) as internet, AVG(safety) as safety, AVG(placement) as placement, AVG(hapiness) as hapiness, AVG(weather) as weather, AVG(fun) as fun, AVG(fests) as fests
FROM college 
GROUP BY collegename
shabang
  • 160
  • 1
  • 13
  • this https://stackoverflow.com/questions/14787561/find-the-average-of-two-combined-columns-in-sql can be usefull for you to read – shabang Aug 17 '17 at 19:58
  • I want to calculate average of each individual column not a combined value – Siddhartha B Aug 17 '17 at 20:09
  • Then for average of each individual column : `SELECT AVG(campus) as campus, AVG(location) as location, AVG(cost) as cost, AVG(internet) as internet, AVG(safety) as safety, AVG(placement) as placement, AVG(hapiness) as hapiness, AVG(weather) as weather, AVG(fun) as fun, AVG(fests) as fests FROM college GROUP BY collegename` – shabang Aug 18 '17 at 12:16