Mysqli / PHP - 显示具有特定值的行数/列中的总行数=百分比

时间:2014-12-10 22:02:50

标签: php mysql mysqli

我是一个mysqli / php新手,所以任何(善意的)帮助都非常感激。 我得到了一个mysql表,列中列出了调查结果。 我需要创建一个表格,显示列中每个值的百分比,例如:

How many assets are in your organization?

Less than $1 million
$1 million - $5 million 
$1 million - $5 million 
Less than $1 million 
Less than $1 million 
Less than $1 million 
$1 million - $5 million 
Less than $1 million 
Less than $1 million 
Less than $1 million 
$1 million - $5 million 
Less than $1 million 
$1 million - $5 million 
Less than $1 million 
Less than $1 million 
$1 million - $5 million 
Less than $1 million 
$1 million - $5 million 
Less than $1 million 
$1 million - $5 million
Less than $1 million
Less than $1 million
Less than $1 million
$200 million - $500 million
...

我需要为每个值生成一个百分比,即

Less than $1 million: 40%
$200 million - $500 million: 20%

等。我知道我需要计算[number of rows with Value A] / [Total Rows],但我不知道该怎么做。有人可以帮忙吗?

编辑:

这是我现在正在使用的代码

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Document</title>
</head>

<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>


<?php

$con=mysqli_connect("localhost","root","root","practice"); 

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT *, COUNT(*) AS percentage, FROM `surveyresults` GROUP BY col19");


echo "<table border='1'>
<tr>
<th>TestQuestion</th
</tr>";


while($row = mysqli_fetch_array($result))

{

echo "<tr>";
echo "<td>" . $row['col19'] . "</td>";
echo "</tr>";

}
echo "</table>";


if (!$result) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

mysqli_close($con);
?>


</body>
</html>

我收到以下PHP错误:

  • 警告:mysqli_fetch_array()要求参数1为mysqli_result,第32行/Applications/MAMP/htdocs/benchmark/mysqltest.php中给出布尔值

  • 错误:您的SQL语法出错;检查与您的MySQL服务器版本相对应的手册,以便在&#39; FROM surveyresults GROUP BY col19&#39;附近使用正确的语法。在第1行

1 个答案:

答案 0 :(得分:0)

您可以使用此查询:

SELECT   *, 
         (COUNT(assets_column) / COUNT(*)) * 100 AS percentage, 
FROM     `TABLE` 
GROUP BY assets_column

也许有更好的方式来写这个,只是一个例子。