2015-04-21 128 views
2

我有数字的表是这样的:功能SQL SUM查询

______________________________________ 
| axle_id | train_id | axle | distance | 
|_________|__________|______|__________| 
| 1  |  1 | 1 | 20 | 
| 2  |  1 | 2 | 50 | 
| 3  |  1 | 3 | 200 | 
| 4  |  1 | 4 | 50 | 
| 5  |  1 | 5 | 200 | 
| 6  |  1 | 6 | 50 | 
| 7  |  1 | 7 | 200 | 
| 8  |  1 | 8 | 50 | 
|_________|__________|______|__________| 

现在我想指望他们,并与SUM计算。 的代码,我现在:

function count_axles($id) { 
     $sql = "SELECT sum(distance)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id"; 
     $sth = $this->pdo->prepare($sql); 
     $sth->bindParam(":train_id", $id, PDO::PARAM_STR); 
     $sth->execute(); 
     return $sth->fetchAll(); 
    } 

而且我通过调用这个函数:

<?php 
     $count_axle = $database->count_axles($_GET['train_id']); 
?> 
<?php  
    foreach($count_axle as $counting){ 
    } 

     echo $counting['totaldistance']; 
?> 

现在的输出是正确的。
(3.2800000000000002)这是25.000
的百分比,但我想补充5000,如:

$sql = "SELECT sum(distance)+(5000)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id"; 

但是,当我这样做,输出随机生成类似:

为什么要这样做,我该如何解决这个问题?

+0

可能会被整数分割。 – duffymo

+3

尝试将'(sum(distance)+(5000))'代替。 – yergo

+0

作品!谢谢:) – Mitch

回答

6

基本数学。你做

     5000 
    sum(distance) + -------------- 
        25000 * 100 

当你真的想

sum(distance) + 5000 
    ------------------------ 
     25000 * 100 

尝试

SELECT (sum(distance)+(5000))/(25000)*(100) 
     ^--------------------^ 

代替。请注意额外的括号。

记住老BEDMAS助记符:括号,指数,除法,乘法,加法,减法...

+0

从学校开始,我们都可能了解到'BODMAS' http://www.mathsisfun.com/operation-order-bodmas.html –

+0

它正在工作!非常感谢你!我可以在9分钟内接受答案 – Mitch

1

尝试用:

$sql = "SELECT (sum(distance)+(5000))/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id"; 

司拥有和操作偏好。