从多个表中选择SUM

时间:2012-08-12 10:31:17

标签: sql sum

当我加入3个表时,我一直得到错误的总和值。 这是表格中ERD的图片:

enter image description here

(原文:http://dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png

以下是查询:

select SUM(gpCutBody.actualQty) as cutQty   , SUM(gpSewBody.quantity) as sewQty
from jobOrder
inner join gpCutHead on gpCutHead.joNum = jobOrder.joNum
inner join gpSewHead on gpSewHead.joNum = jobOrder.joNum
inner join gpCutBody on gpCutBody.gpCutID = gpCutHead.gpCutID
inner join gpSewBody on gpSewBody.gpSewID = gpSewHead.gpSewID

2 个答案:

答案 0 :(得分:4)

如果您所有订单的削减和缝制数量感兴趣,那么最简单的方法就是这样:

select (select SUM(gpCutBody.actualQty) from gpCutBody) as cutQty, 
       (select SUM(gpSewBody.quantity) from gpSewBody) as sewQty

(这假设裁剪和缝制将始终具有相关的作业单。)

如果您想按工作订单查看裁员和缝制的细分,可能会更喜欢这样的事情:

select joNum, SUM(actualQty) as cutQty, SUM(quantity) as sewQty
from (select joNum, actualQty, 0 as quantity
      from gpCutBody
      union all
      select joNum, 0 as actualQty, quantity
      from gpSewBody) sc
group by joNum

答案 1 :(得分:3)

马克的做法很好。我想建议在联盟之前做分组的替代方案,仅仅因为这可以是一种更通用的方法来进行多个维度的求和。

您的问题是,您有两个要求相加的维度,并且您正在获得联接中值的叉积。

select joNum, act.quantity as ActualQty, q.quantity as Quantity
from (select joNum, sum(actualQty) as quantity
      from gpCutBody
      group by joNum
     ) act full outer join
     (select joNum, sum(quantity) as quantity
      from gpSewBody
      group by joNum
     ) q
     on act.joNum = q.joNum

(我保留Mark的假设,即通过joNum执行此操作是所需的输出。)