【问题标题】:Percentage for each result where id = idid = id 的每个结果的百分比
【发布时间】:2015-05-11 08:02:27
【问题描述】:

在我的数据库中,我有一个如下所示的表:

现在,在我的 php 代码中,我做了一个这样的 SUM:

function number_of_axless() {
        $sql = "SELECT (sum(distance))/(25000)*(100) as totaldistance1 FROM axle WHERE train_id = :train_id";
        $sth = $this->pdo->prepare($sql);
        $sth->bindParam(':train_id', $_GET['train_id'], PDO::PARAM_STR);
        $sth->execute();
        return $sth->fetchAll();
    }

还有:

<?php
    $number_of_axles = $database->number_of_axless();

    foreach($number_of_axles as $number_ofaxles){
        echo $number_ofaxles['totaldistance1'];
    }
?>

现在我得到结果:40. (40%)

但我想要的是显示 4 个结果。有 4 个不同的数字。

所以:

轴 1 = 0 所以它应该是 0%
轴 2 = 2500 所以应该是 10%
轴 3 = 5000 所以应该是 30%
轴 4 = 2500 所以应该是 40%

我该怎么做?

现在所有的车轴都是 40%。

【问题讨论】:

    标签: php html for-loop mysqli sum


    【解决方案1】:

    我会在 php 循环中进行求和,而不是在 sql 中(ORDER BY 子句在这里也很重要):

    $sql = "SELECT distance FROM axle WHERE train_id = :train_id ORDER BY axle ASC";
    
    ...
    
    $total_distance = 0;
    foreach($number_of_axles as $number_ofaxles){
        $total_distance += $number_ofaxles['distance'];
        echo $total_distance/25000*100;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多