php mysql计算每个百分比

时间:2011-03-31 15:15:34

标签: php mysql

如何为每个用户计算mysql的百分比?

$q = $db->query("SELECT * FROM report LEFT JOIN user ON user.user_id= report.id_user WHERE date='$today' GROUP BY id_user");
$q1 = $db->query("SELECT SUM(r_amount) AS total FROM report WHERE date='$today' AND id_user=id_user");
$r1 = $q1->fetch_assoc();
$totalCharge = $r1['totalCharge'];
$sixtyPercent = $totalCharge * 0.60;
$fortyPercent = $totalCharge * 0.40;

while($r = $q->fetch_array(MYSQLI_ASSOC)) :
    echo '<tr>';
    echo '<td>'.$r['user_name].'</td>';
    echo '<td align="center">'.$fortyPercent.'</td>';
    echo '<td align="center">'.$sixtyPercent.'</td>';
    echo '<td align="center"><strong></strong></td>';
    echo '</tr>';
endwhile;


current result:

name     60% cut    40% cut    total 
user 1   60         40         100
user 2   60         40         100
user 3   60         40         100

expecting result:

name     60% cut    40% cut    total 
user 1   60         40         100
user 2   24         16         40
user 3   48         32         80

1 个答案:

答案 0 :(得分:1)

您没有获得预期的结果,因为您的$totalCharge变量永远不会更改(也不会匹配正确的user_id)。

你很可能想要做的是编写一个SQL语句,它结合了你当前拥有的两个语句,然后简单地遍历该语句的结果并在该循环中完成所有计算。

SQL语句可能类似于:

SELECT SUM(r_amount) AS totalCharge, report.*, user.* 
FROM report 
JOIN total ON total.id_user = report.id_user 
LEFT JOIN user ON user.user_id= report.id_user 
WHERE date='$today' GROUP BY user_id

您可能需要稍微调整一下才能获得预期效果。

然后你的循环看起来像:

while($r = $q->fetch_array(MYSQLI_ASSOC)) {
    $totalCharge = $r['totalCharge'];
    $sixtyPercent = $totalCharge * 0.60;
    $fortyPercent = $totalCharge * 0.40;
    echo '<tr>';
    echo '<td>'.$r['user_name'].'</td>';        // corrected syntax error here
    echo '<td align="center">'.$sixtyPercent.'</td>';
    echo '<td align="center">'.$fortyPercent.'</td>';
    echo '<td align="center"><strong></strong></td>';
    echo '</tr>';
}

希望这能指导您解决问题。