2015-04-21 122 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"; 

司擁有和操作偏好。