如何使用php计算mysql数据库的百分比?

vktxenjb  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(198)

我有一张table叫 feedbacks 看起来是这样的:

id    user    type
1    JOhnT  Positive
2    JOhnT  Negative
3    Sarah  Positive
4    JOhnT  Positive
5    JOhnT  Neutral
....................

我要去拿那个 percentagePOSITIVE 为每个使用php的用户提供反馈。
我试过这样的方法,我知道这是错误的:

$sql = "SELECT type, count(*), 
concat(round(( count(*)/(SELECT count(*) FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE') * 100 ),2),'%') AS percentage 
FROM feedback 
WHERE user='$email' AND type='positive' GROUP BY type";
$query = mysqli_query($db_conx, $sqlJ);

echo $sql;

有人能给我一些建议吗?
编辑:
根据这些评论,我到目前为止得到的是:

$sql = "SELECT * FROM feedbacks WHERE user='JOhnT' AND type='POSITIVE'";

$query = mysqli_query($db_conx, $sql) or die(mysqli_error($db_conx));

$productCount = mysqli_num_rows($query);

if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

 ///do I need to calculate the percentage here?//
//if so, how?////

}
}

我最终创建了一个数组,并将整个循环中的每一行$都放入数组中,然后按如下方式计算百分比:

$c = count($values);
    $array = $values;       
    function array_avg($array, $round=1){
    $num = count($array);
    return array_map(
        function($val) use ($num,$round){
            return array('count'=>$val,'avg'=>round($val/$num*100, $round));
        },
        array_count_values($array));
}

$rating = 0;                    

if($c > 0){
$avgs = array_avg($array);
$rating = $avgs["positive"]["avg"];
}

现在还可以。

mo49yndu

mo49yndu1#

你可以做一个条件平均。在mysql中,您可以这样表述:

select user, avg(type = 'Positive') positive_ratio
from feedback
group by user

这给了你,每一个 user ,值介于 0 以及 1 这代表了 type s。你可以把它乘以 100 如果你想要一个百分比。
如果要为单个用户提供此信息,可以使用 where 条款(无需 group by ):

select user, avg(type = 'Positive') positive_ratio
from feedback
where user = 'JOhnT'

旁注: user 是一个mysql关键字,因此不是一个好的列名选择。

相关问题