如何从2x LEFT JOIN计算字段数据

时间:2012-08-14 13:37:37

标签: mysql sql left-join

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

这些工作本身很好,但添加'qry3',应该将'qry2'的答案与'qry1'分开并给出平均柴油消耗,但我不知道如何使用每个的输出这些LEFT JOIN和使用结果进行(应该是非常简单的)计算:

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` 

我一直在犯错误,我尝试了一些搜索,但仍然空着......

2 个答案:

答案 0 :(得分: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`

答案 1 :(得分: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()。