我有个问题。
我有这两张表,需要计算每张表一列的总和。
表与零件号有关系。
问题是每个表返回多个值。
物料清单

id  finishgood  partnumber  qty
1   F1920-10    3122E       3
2   F1920-10    AE3030      4
3   F1920-10    3122E       2
4   F1920-10    5538WM      1
5   F1920-10    9803K       2
6   F1920-10    9722F       1
7   F1920-10    9722F       2
8   F1920-10    1001A       1
9   E2020-10    AB123       2

作为项目的库存项目
id  partnumber  LOT     onHand
1   3122E       M01     105
2   3122E       M10     23
3   AE3030      M02     30
4   5538WM      M02     15
5   9803K       M10     133
6   9722F       M15     45
7   9722F       M30     55
8   9722F       M01     150
9   1001A       M10     NULL

这是我的问题
SELECT bom.finishgood, bom.partnumber, SUM(bom.qty), SUM(item.onHand)
FROM bom
left outer join item ON item.partnumber = bom.partnumber
WHERE bom.partnubmer = 'F1920-10'
GROUP BY bom.partnumber

这是我的结果
partnumber  sum(qty)    ERROR   sum(onHand)
3122E       10          5*2     128
AE3030      3           ok      30
5538WM      1           ok      15
9803K       2           ok      133
9722F       9           3*3     250

在添加更多值时,将添加到另一个表中的行。
这是理想的结果
partnumber  sum(bom.qty)    sum(items.onHand)
3122E       5           128
AE3030      3           30
5538WM      1           15
9803K       2           133
9722F       3           250

他们知道吗?
我很沮丧
谢谢你的回答。

最佳答案

SELECT
    DerivedTotalByPart.PartNumber AS [partnumber],
    [BOM Total] AS [sum(bom.qty)],
    DerivedTotalOnHand.TotalOnHand AS [sum(items.onHand)]
FROM
    (
    SELECT
        bom.partNumber AS [PartNumber],
        SUM(bom.qty) AS [BOM Total]
    FROM
         bom
    WHERE
        bom.finishgood = 'F1920-10'
    GROUP BY
        bom.partNumber
    ) DerivedTotalByPart
    LEFT OUTER JOIN
    (
    SELECT
        partnumber,
        ISNULL(SUM(onhand), 0) AS [TotalOnHand]
    FROM
        item
    GROUP BY
        partnumber
    ) DerivedTotalOnHand ON DerivedTotalByPart.PartNumber = DerivedTotalOnHand.PartNumber

10-04 12:38