将3个相关表中的总计汇总到父表 - SQL

时间:2017-10-16 16:20:23

标签: sql join subquery

我有一份工作单表,其中有3个相关的人工,设备和材料表。我试图通过WorkOrderID来计算3个项目和组的成本。我知道直接连接将乘以所有结果,所以我需要使用子查询,但我无法弄清楚如何编写任何子查询。

以下是断开的直接连接查询。我尝试了一些子查询并不断获得成倍增长的结果。任何帮助是极大的赞赏。谢谢。

select wo.workorderid, sum(lab.cost) as labcost, sum(mat.cost) as matCost, sum(eq.cost) as eqcost
 from WORKORDER as wo
    join LABORCOSTACT as lab
 on lab.WORKORDERID = wo.WORKORDERID
    join MATERIALCOSTACT as mat
 on mat.WORKORDERID = wo.WORKORDERID
    join EQUIPMENTCOSTACT as eq
 on eq.WORKORDERID = wo.WORKORDERID
 where lab.TASKNAME like 'tree_rmvl'
group by wo.WORKORDERID
order by wo.WORKORDERID

1 个答案:

答案 0 :(得分:0)

如果你想避免可能的重复,你可以通过加入主表的键加入每个表组的结果

select wo.workorderid, lab.tot_lab_cost as labcost, mat.tot_mat_cost as matCost, eq.tot_eq_cost) as eqcost
from WORKORDER as wo
  inner join  ( 
        select WORKORDERID , sum(cost) tot_lab_cost
        from LABORCOSTACT 
        group by WORKORDERID
    ) lab on lab.WORKORDERID = wo.WORKORDERID
  inner join (
        select WORKORDERID , sum(cost) tot_mat_cost
        from MATERIALCOSTACT
        group by WORKORDERID
    ) mat on mat.WORKORDERID = wo.WORKORDERID
  inner join (
        select WORKORDERID , sum(cost) tot_eq_cost
        from EQUIPMENTCOSTACT
        group by WORKORDERID
     ) eq on eq.WORKORDERID = wo.WORKORDERID
 where lab.TASKNAME like 'tree_rmvl'
order by wo.WORKORDERID