1

我需要计算我们工厂的燃料消耗量。我的查询是 LEFT JOIN,第一个“qry1”计算工厂当月运行的总小时数,“qry2”计算每个工厂使用的总柴油。

这些可以自己正常工作,但是添加“qry3”,它应该将“qry2”的答案与“qry1”分开并给出平均柴油消耗量,但我不知道如何使用这些 LEFT 的输出加入并使用结果进行(应该很容易)计算:

SELECT 
 `plant`.`plant_id`,
 `qry1`.`total_hrs`, 
 `qry2`.`total_d`, 
 `qry3`.`consumption`

FROM `plant` 

  LEFT JOIN ( 
   SELECT (MAX(`plant_hrs_stop`)- MIN(`plant_hrs_start`) ) AS total_hrs, `plant_id` 
   FROM`plant_hrs`  
   WHERE MONTH(`plant_hrs_date`)= MONTH( CURRENT_DATE )  
   GROUP BY`plant_id` 
  ) AS `qry1` ON `plant`.`plant_id`=`qry1`.`plant_id` 

  LEFT JOIN ( 
   SELECT (SUM(`diesel_qty`) ) AS total_d, `diesel_vehicle_no` AS `plant_id` 
   FROM`diesel`  
   WHERE MONTH(`diesel_date`)= MONTH( CURRENT_DATE )  
   GROUP BY `diesel_vehicle_no` 
  ) AS `qry2` ON `plant`.`plant_id`=`qry2`.`plant_id` 

  LEFT JOIN ( 
   SELECT (`qry2`.`total_d` / `qry1`.`total_hrs`) AS consumption,    
   FROM `qry1`, `qry2`  
   GROUP BY `plant_id` 
  ) AS `qry3` ON `plant`.`plant_id`=`qry3`.`plant_id`

ORDER BY `plant`.`plant_id` 

我不断收到错误,我尝试了一些搜索,但一直出现空...

4

2 回答 2

1

您不需要最后一次加入。 并确保qry1.total_hrs <> 0

SELECT 
 `plant`.`plant_id`,
 `qry1`.`total_hrs`, 
 `qry2`.`total_d`, 
 `qry3`.`consumption`,
  if(COALESCE(`qry1`.`total_hrs`,0)<>0,'qry2`.`total_d` / `qry1`.`total_hrs`,NULL) AS consumption

FROM `plant` 

  LEFT JOIN ( 
   SELECT (MAX(`plant_hrs_stop`)- MIN(`plant_hrs_start`) ) AS total_hrs, `plant_id` 
   FROM`plant_hrs`  
   WHERE MONTH(`plant_hrs_date`)= MONTH( CURRENT_DATE )  
   GROUP BY`plant_id` 
  ) AS `qry1` ON `plant`.`plant_id`=`qry1`.`plant_id` 

  LEFT JOIN ( 
   SELECT (SUM(`diesel_qty`) ) AS total_d, `diesel_vehicle_no` AS `plant_id` 
   FROM`diesel`  
   WHERE MONTH(`diesel_date`)= MONTH( CURRENT_DATE )  
   GROUP BY `diesel_vehicle_no` 
  ) AS `qry2` ON `plant`.`plant_id`=`qry2`.`plant_id` 

ORDER BY `plant`.`plant_id`
于 2012-08-14T13:48:33.457 回答
0

您不需要另一个连接来进行最终计算,您可以这样做:

select `plant`.`plant_id`,
    `qry1`.`total_hrs`,
    `qry2`.`total_d`,
    (`qry2`.`total_d` / `qry1`.`total_hrs`) as consumption
from `plant`
left join (
    select (MAX(`plant_hrs_stop`) - MIN(`plant_hrs_start`)) as total_hrs,
        `plant_id` 
    FROM`plant_hrs`
    where MONTH(`plant_hrs_date`) = MONTH(current_date)
    group by `plant_id`
    ) as `qry1` on `plant`.`plant_id` = `qry1`.`plant_id`
left join (
    select (SUM(`diesel_qty`)) as total_d,
        `diesel_vehicle_no` as `plant_id`
    from `diesel`
    where MONTH(`diesel_date`) = MONTH(current_date)
    group by `diesel_vehicle_no`
    ) as `qry2` on `plant`.`plant_id` = `qry2`.`plant_id`
order by `plant`.`plant_id`

请注意,仅在 where 子句中使用 MONTH 意味着您将获得超过一年的数据。如果这不是预期的,也请使用 YEAR()。

于 2012-08-14T13:40:31.640 回答