来自多个表的sql sum数据

时间:2010-04-07 09:49:25

标签: sql join ms-jet-ace

我有2个表AP和INV,其中两个都有[PROJECT]和[Value]。

我想要一个查询返回这样的内容:

项目| SUM_AP | SUM_INV

我想出了下面的代码,但它返回了错误的结果(总和是错误的)。

SELECT AP.[PROJECT],
SUM(AP.Value) AS SUM_AP, 
SUM(INV.Value) AS SUM_INV
FROM AP INNER JOIN INV ON (AP.[PROJECT] =INV.[PROJECT])
WHERE AP.[PROJECT] = 'XXXXX'
GROUP BY AP.[PROJECT]

6 个答案:

答案 0 :(得分:13)

您的查询结果是错误的,因为您尝试汇总的值正在分组,这会导致重复值包含在SUM中。

您可以通过几个子选择来解决它:

SELECT 
    AP1.[PROJECT],
    (SELECT SUM(AP2.Value) FROM AP AS AP2 WHERE AP2.PROJECT = AP1.PROJECT) AS SUM_AP,
    (SELECT SUM(INV2.Value) FROM INV AS INV2 WHERE INV2.PROJECT = AP1.PROJECT) AS SUM_INV
FROM AP AS AP1 
    INNER JOIN INV AS INV1 
        ON (AP1.[PROJECT] =INV1.[PROJECT])
WHERE AP1.[PROJECT] = 'XXXXX'
GROUP BY AP1.[PROJECT]

答案 1 :(得分:2)

如果AP中的N行具有给定的项目ID,并且INV中的M行具有该ID,则项目ID上的两个表之间的联接将总计为{ {1}}该项目的行,因为对于具有该项目ID的INV中的每一行,将重复AP中的相同行,反之亦然。因此,为什么你的计数最有可能是关闭的(因为由于连接的重复,它会多次计算给定表中的同一行)。

相反,您可能想尝试在两个子查询的结果之间进行连接,一个按项目ID对第一个表进行分组,并将其与总和进行分组,第二个按项目ID对另一个表进行分组并进行总和 - 然后加入一旦你只有1行,每个项目ID的总和。

答案 2 :(得分:0)

如果PROJECT是父表,则应从项目表中选择FROM,并在两个子表上执行左外连接:

SELECT PROJECT.PROJECT_ID, SUM(AP.Value) AS SUM_AP, SUM(INV.Value) AS SUM_INV
FROM PROJECT
LEFT OUTER JOIN AP ON (AP.[PROJECT] = PROJECT.[PROJECT_ID])
LEFT OUTER JOIN INV ON (INV.[PROJECT] = PROJECT.[PROJECT_ID])
WHERE PROJECT.[PROJECT_ID] = 'XXXXX'
GROUP BY PROJECT.[PROJECT_ID]

答案 3 :(得分:0)

您可以将两个总和计算分开。我能想到的一种方法是将库存计算移动到子查询,例如:

SELECT 
    AP.[PROJECT]
,   SUM(AP.Value) AS SUM_AP
,   SummedInv as SUM_INV
FROM AP
LEFT JOIN (
    SELECT PROJECT, SUM(Value) AS SUM_INV
    FROM INV
    GROUP BY PROJECT
) SummedInv ON SummedInv.Project = AP.Project
GROUP BY AP.PROJECT, SummedInv.SUM_INV

由于SummedInv子查询已在project上分组,因此在外部查询中对SummedInv.SUM_INV进行分组也是安全的。

答案 4 :(得分:0)

这个查询怎么样:

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


where jobOrder.joNum = '36'

这是指向ERD的链接:http://dl.dropbox.com/u/18794525/AUG%207%20DUMP%20STAN.png

答案 5 :(得分:-1)

尝试:

SELECT AP.[PROJECT] AS PROJECT, SUM(AP.[Value]) AS SUM_AP, SUM(INV.[Value]) AS SUM_INV
FROM AP, INV
WHERE AP.[PROJECT] = INV.[PROJECT]
AND AP.[PROJECT] = 'XXXXX'
GROUP BY AP.[PROJECT]