计算过去30天的平均燃料

时间:2014-05-03 13:11:11

标签: php mysql average

我有一个脚本可以计算过去30天的平均油耗,但有些用户在计算中报告错误。

这就是我所拥有的:

//Calculate the total km for the last 30 days
    $result = mysqli_query($con,"SELECT MIN(km) AS minikm, MAX(km) AS maxkm FROM diesel WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid']." ORDER BY diesel.dato DESC");
    while($row = mysqli_fetch_array($result)){ $mileage = $row['maxkm'] - $row['minikm'];}

//Sum up all the Liters of diesel
    $result = mysqli_query($con,"SELECT SUM(liter) AS totalfuel FROM diesel WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid']." ORDER BY diesel.dato DESC");
    while($row = mysqli_fetch_array($result)){ $totalfuel = $row['totalfuel'];} 

$averagefuel = $totalfuel / $mileage * 10;

在对此进行故障排除时,我注意到我不应该在计算的第一条记录中包含升。只有总公里。那我怎么能这样做呢?

2 个答案:

答案 0 :(得分:2)

如果我不得不推测用户的想法,问题是一个月内的燃料输入与本月的燃料消耗有些无关。换句话说,坦克可以开满空或介于其间。并且,它可能会结束空,满或介于两者之间。

这意味着您的计算可能会被任何一方的油箱充满油量。

现在,这可以通过特殊情况得到缓解。例如,也许车辆每天都在行驶,他们的油箱在一天结束时被装满。因此,在午夜,你有一个合理的假设,坦克已经满了。如果是这种情况我会感到惊讶,因为汽车中的燃料库存需要花钱。他们可以雇用我作为顾问来改善他们的资产负债表;)(仅仅是为了记录,这不是我的专长)。

作为一个小注释,您可以在SQL中进行完整计算。您不需要使用两个查询或任何客户端计算:

SELECT 10 * SUM(liter) / (MAX(km) - MIN(km)) as AvgFuel
FROM diesel
WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid'].";

答案 1 :(得分:0)

我认为你需要一直加上里程。试试这个:

//Calculate the total km for the last 30 days
$mileage = 0;
    $result = mysqli_query($con,"SELECT MIN(km) AS minikm, MAX(km) AS maxkm FROM diesel WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid']." ORDER BY diesel.dato DESC");
    while($row = mysqli_fetch_array($result)){ $mileage += $row['maxkm'] - $row['minikm'];}

//Sum up all the Liters of diesel
    $result = mysqli_query($con,"SELECT SUM(liter) AS totalfuel FROM diesel WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid']." ORDER BY diesel.dato DESC");
    while($row = mysqli_fetch_array($result)){ $totalfuel = $row['totalfuel'];} 

$averagefuel = $totalfuel / $mileage * 10;

Gordon Linoff为您提供了良好的解决方案。试着用这个:

//Calculate the total km for the last 30 days
$mileage = 0;
$result = mysqli_query($con,
"SELECT 10 * SUM(liter) / (MAX(km) - MIN(km)) as AvgFuel
FROM diesel
WHERE diesel.dato >= '$dx' AND userid = ".$_COOKIE['userid']);
$averagefuel = $steps = 0; 
while($row = mysqli_fetch_array($result)){ 
    $averagefuel += $row['AvgFuel']; 
    $steps++; 
} 
$averagefuel = $averagefuel/$steps;