2

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

在此处输入图像描述

(原文: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
4

2 回答 2

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
于 2012-08-12T10:49:19.997 回答
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 执行此操作是所需的输出。)

于 2012-08-12T14:36:55.680 回答