【问题标题】:How to calculate average of a SQL Column in php by Group Id and display on HTML Page?如何按组 ID 计算 php 中 SQL 列的平均值并显示在 HTML 页面上?
【发布时间】:2017-08-17 19:31:28
【问题描述】:

我想计算所有其他按大学名称分组的列的平均值。 即 RVCE 与所有其他列的平均值, BMS 与所有其他列的平均值等 并在 HTML 中显示值。

SQL Database Structure Image

我尝试了以下代码,但它没有返回任何值。

<?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>";
}
?>

【问题讨论】:

  • 原始查询在 mySQL 中工作正常吗?
  • 我收到错误“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册以获取正确的语法以使用 nea 'SELECT Collegename AVG(campus) AS avg_campus FROM College GROUP BY Collegename' 在第 2 行
  • 校园栏的数据类型?
  • 除学院名外都是 int(11)
  • 你能在 SQLFiddle 或 rextester 中重新创建错误吗?语法是正确的,肯定有别的事情发生了……

标签: php html mysql


【解决方案1】:

试试这个?

<?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>";
}
?>

【讨论】:

  • @SiD 甚至 collegename 是空白的?
  • 是的,没有任何显示
  • @SiddharthaB 好的尝试更新的,添加端口并使用127.0.0.1作为主机(应该与本地主机相同),同样mysql使用小写
【解决方案2】:
SELECT
     AVG((campus + location + cost + internet + safety + placement + hapiness + weather + fun + fests)/10) as avg_campus,
   FROM
     college
   GROUP BY
     collegename

如果大学名称只有一行,那么 group by 就没有用了,而且...... AVG() 也是如此

对于每一列的平均值:

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

【讨论】:

  • 这个stackoverflow.com/questions/14787561/…对你阅读很有帮助
  • 我想计算每个单独列的平均值而不是组合值
  • 然后是每个列的平均值: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
猜你喜欢
  • 2021-07-07
  • 2018-11-14
  • 2014-06-21
  • 2022-01-05
  • 2017-04-18
  • 2021-12-11
相关资源
最近更新 更多