7

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

我想要一个查询返回如下内容:

项目 | SUM_AP | SUM_INV

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

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]
4

6 回答 6

18

您的查询结果是错误的,因为您尝试汇总的值正在分组,这会导致重复值包含在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]
于 2010-04-07T10:00:45.130 回答
2

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

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

于 2010-04-07T09:56:56.257 回答
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]
于 2010-04-07T10:29:23.977 回答
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在外部查询中分组也是安全的。

于 2010-04-07T10:33:50.537 回答
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

于 2012-08-12T10:33:41.660 回答
-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]
于 2010-04-07T10:05:04.923 回答