我想计算表中每辆车的平均油耗。我有一个spendforfuel
带有IdCar
, Odometer
,Quantity
字段的表。里程表字段是当前里程。数量是当前里程和上次检测到的里程之间消耗的升数。
这是我的公式:
100 / ( (MAX(Odometer) - MIN(Odometer)) / (SUM(Quantity) - FIRST(Quantity) ) )
这是我所做的:
$q = $this->db->select()
->from(array('s1' => 'spendforfuel'), array('fuel_consumption' => '100 / ( s2.odometer_sum / ( s3.quantity_sum - s4.first_quantity ) )'))
->joinLeft(array('s2' => 'spendforfuel'), 's2.IdCar = s1.IdCar', array('odometer_sum' => 'MAX(s2.Odometer) - MIN(s2.Odometer)'))
->joinLeft(array('s3' => 'spendforfuel'), 's3.IdCar = s1.IdCar', array('quantity_sum' => 'SUM(s3.Quantity)'))
->joinLeft(array('s4' => 'spendforfuel'), 's4.IdCar = s1.IdCar', array('first_quantity' => 's4.Quantity'))
->where('s4.Odometer > ?', 0)
->limit('1 ASC')
->group('s1.CarId')
->where('s1.CarId = ?', 76);
我不确定我是否必须使用连接。有任何想法吗?