mysql的计算结果是一样的

时间:2014-03-25 16:13:11

标签: mysql database

我有以下查询:

select v.vehicle_id, 
       v.year, 
       v.make, 
       v.model, 
       v.mileage, 
       count(distinct o.order_id) as order_number, 
       sum(s.labor_hour*labor_cost_per_hour+part_cost) * 
       count(distinct vo.order_id) as vehicle_cost

   from tbl_vehicle_order vo
  inner join tbl_vehicle v 
    on vo.vehicle_id = v.vehicle_id
  inner join tbl_order o
    on vo.order_id = o.order_id
  natural join tbl_customer c
  natural join tbl_service s
  natural join tbl_rate r
where 
      s.rate_id = r.rate_id 
  and vo.order_id = o.order_id 
  and vo.vehicle_id=v.vehicle_id
group by v.vehicle_id;

结果是这样=> enter image description here

更新: 在我编辑我的代码后,似乎结果并没有太大变化。 这是更新的代码:

 select v.vehicle_id, v.year, v.make, v.model, v.mileage, count(vo.order_id) as order_number, sum(s.labor_hour*r.labor_cost_per_hour+s.part_cost) as vehicle_cost
 from tbl_vehicle_order vo, tbl_vehicle v,tbl_order o,tbl_customer c,tbl_service s,tbl_rate r, tbl_order_service os
 where vo.order_id = o.order_id and vo.vehicle_id = v.vehicle_id and os.service_id = s.service_id and s.rate_id = r.rate_id
 group by v.vehicle_id
 order by 1;

更新结果:   enter image description here

我认为我的计算部分存在一些错误。有人想指出我的错误吗?谢谢!

1 个答案:

答案 0 :(得分:1)

你可以试试这个。它假定您在其他question

中描述的架构
SELECT v.vehicle_id, 
       v.year, 
       v.make, 
       v.model, 
       v.mileage, 
       COUNT(DISTINCT vo.order_id) as unique_orders, 
       SUM(order_summation.order_cost) as sum_of_all_orders
FROM tbl_vehicle_order vo
INNER JOIN tbl_vehicle v 
  ON vo.vehicle_id = v.vehicle_id
JOIN (
    SELECT os.order_id as order_id
      , SUM(s.part_cost + s.labor_hour*r.labor_cost_per_hour) AS order_cost
    FROM order_service AS os
    JOIN service AS s
     ON os.service_id = s.service_id
    JOIN tbl_rate AS r
     ON r.rate_id = s.rate_id
    GROUP BY os.order_id) AS order_summation
  ON order_summation.order_id = vo.order_id
GROUP BY v.vehicle_id, 
         v.year, 
         v.make, 
         v.model, 
         v.mileage;