我有一个相当于中等和整体的产品星级评估系统
示例:
0.5
- 1
- 1.5
- 2
- 2.5
- 3
- 3.5
- 4
- 4.5
- 5
我正确地获取数据中的两个数据,并将两个值相加
从以下咨询:
//we define in a variable the id of the product valued by the valuation system
$id_product = 1;
//we obtain an average and integer value equivalent to 4.5 and 5
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(4.5,5)");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($sum);
while ($stmt->fetch()) {
echo $sum;
}
//we obtain an average and integer value equivalent to 3.5 and 4
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(3.5,4)");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($sum);
while ($stmt->fetch()) {
echo $sum;
}
//we obtain an average and integer value equivalent to 2.5 and 3
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(2.5,3)");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($sum);
while ($stmt->fetch()) {
echo $sum;
}
//we obtain an average and integer value equivalent to 1.5 and 2
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(1.5,2)");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($sum);
while ($stmt->fetch()) {
echo $sum;
}
//we obtain an average and integer value equivalent to 0.5 and 1
$stmt = $con->prepare("SELECT SUM(rating) as total FROM ratings WHERE id_product=? AND rating in(0.5,1)");
$stmt->bind_param("i",$id_product);
$stmt->execute();
$stmt->bind_result($sum);
while ($stmt->fetch()) {
echo $sum;
}
现在我的问题是如何以百分比正确计算数据并得到如下图所示的结果:
答案 0 :(得分:0)
该表中的百分比基于计数,而不是评级值的总和。
您可以在一个查询中完成所有这些操作,您不需要为每个评估范围单独查询。
$stmt = $con->prepare('
SELECT SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star,
SUM(rating IN (3.5, 4))/COUNT(*)*100 AS pct_4_star,
SUM(rating IN (2.5, 3))/COUNT(*)*100 AS pct_3_star,
SUM(rating IN (1.5, 2))/COUNT(*)*100 AS pct_2_star,
SUM(rating IN (0.5, 1))/COUNT(*)*100 AS pct_1_star,
AVG(rating) AS avg_rating
FROM ratings
WHERE id_product = ?');
$stmt->bind_param('i', $id_product);
$stmt->execute();
$percents = array(;
$stmt->bind_result($percents[5], $percents[4], $percents[3], $percents[2], $percents[1], $avg_rating);
if ($stmt->fetch()) {
for ($i in array(5, 4, 3, 2, 1)) {
echo "%i stars: " . round($percents[$i]) . "%<br>";
}
echo "Average rating: $avg_rating<br>";
} else {
echo "This product is not yet rated<br>";
}