[英]function SQL SUM query
I have a table with numbers like this: 我有一个像这样的数字表:
______________________________________
| 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 |
|_________|__________|______|__________|
Now i want to count them and make a calculation with SUM. 现在我想计算它们并用SUM进行计算。 The code i have right now: 我现在的代码:
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();
}
And i call this function via: 我通过以下方式调用此函数:
<?php
$count_axle = $database->count_axles($_GET['train_id']);
?>
<?php
foreach($count_axle as $counting){
}
echo $counting['totaldistance'];
?>
Now the output is correct. 现在输出是正确的。
(3.2800000000000002) This is the percentage of 25.000 (3.2800000000000002)这是25.000的百分比
But i want to add 5000 like: 但我想添加5000像:
$sql = "SELECT sum(distance)+(5000)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
But when i do that, the output generates something randomly like: 840 但是当我这样做时,输出产生一些随机的东西,如: 840
Why does it do this, and how do i solve this? 为什么会这样做,我该如何解决这个问题?
Basic math. 基础数学。 You're doing 你在做
5000
sum(distance) + --------------
25000 * 100
when you really want 什么时候你真的想要
sum(distance) + 5000
------------------------
25000 * 100
Try 尝试
SELECT (sum(distance)+(5000))/(25000)*(100)
^--------------------^
instead. 代替。 Note the extra brackets. 注意额外的括号。
And remember the old BEDMAS mnemonic: brackets, exponents, division, multiplication, addition, subtraction... 并记住旧的BEDMAS助记符:括号,指数,除法,乘法,加法,减法......
Try with: 试试:
$sql = "SELECT (sum(distance)+(5000))/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
Division has preference over sum operations. 部门优先考虑和操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.