我在数据库中有一个表,当前正在使用SELECT语句提取数据,其中“意见”列中的信息等于“否”或“肯定”。
我还想做的是输出正数据作为整体百分比,但是不确定是否有可能我查看了多个溢出问题,但什么也没看到。任何帮助将不胜感激。
$sql = "select Opinion from survey where Opinion = 'Positive'";
$result = mysqli_query($con, $sql);
if (!$result) {
die(mysqli_error($con));
}
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Date</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
}
} else {
echo "0 results";
}
?>
答案 0 :(得分:1)
该查询将计算与“调查”表的总行相比,“正面”意见的百分比:
select (SUM(IF(Opinion = 'Positive',1,0))/count(*))*100 as percentage_positive
from survey
下面的查询可以一次确定每种不同意见的百分比:
select
Opinion,
count(*) as total,
(count(*) / (select count(*) from survey))*100 as percentage
from survey
group by opinion
答案 1 :(得分:0)
像SQL查询这样的东西吗?
SELECT COUNT(Opinion) / (SELECT COUNT(Opinion) FROM survey) * 100
FROM survey
WHERE Opinion = 'Negative'
答案 2 :(得分:0)
在Kevin HR的帮助下,我使用下面的代码解决了我的问题。
$sql = "select Opinion,count(*) as total,(count(*) / (select count(*) from survey))*100 as percentage from survey group by opinion";
$result = mysqli_query($con, $sql);
echo "<div style='overflow: auto;'>";
echo "<table width=40% border=1 align=center >
<tr>
<th>Opinion</th>
<th>Percentage</th>
</tr>";
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<tr align=center>';
echo "<td>" . $row['Opinion'] . "</td>";
echo "<td>" . $row['percentage'] . "</td>";
}
}
else {
echo "0 results";
}
答案 3 :(得分:0)
用于从数据库获取行数值的工作代码
$sql = "SELECT * FROM `survey` WHERE Opinion='Positive'";
$connStatus = $con->query($sql);
$numberOfRows = mysqli_num_rows($connStatus);
echo "There are a total number of $numberOfRows Positive rows in the database";
echo "<br>";
echo "<br>";