我正在使用此查询来获取贴纸的使用百分比(pdo):
SELECT
id_sticker,
CAST((COUNT(*) / :stickers_count * 100) AS UNSIGNED) as percentage
FROM user_sticker AS sticker_total
WHERE id_user_to = :id_user
GROUP BY id_sticker
ORDER BY percentage DESC
这是最终结果:
{
"data": [
{
"id_sticker": 2,
"percentage": 28.5714285714
},
{
"id_sticker": 1,
"percentage": 14.2857142857
},
{
"id_sticker": 3,
"percentage": 14.2857142857
},
{
"id_sticker": 5,
"percentage": 14.2857142857
},
{
"id_sticker": 6,
"percentage": 14.2857142857
},
{
"id_sticker": 7,
"percentage": 14.2857142857
}
]
}
百分比的总和是 99.9999999999 ...它应该是 100(这会触发我正在使用的饼图组件的错误)。有任何想法吗?谢谢!
解决方案
抓取数据后,我结束了添加这个 php 修复:
$dif = 100;
foreach($result as $item) {
$dif = $dif - $item['percentage'];
}
if($dif > 0) {
$result[0]['percentage'] += $dif;
} elseif($dif < 0) {
$result[count($result)-1]['percentage'] += $dif;
}