聚合函数返回不准确的结果

时间:2016-08-01 06:36:14

标签: sql sql-server sql-server-2008

我正在努力获得物品余额

MotionEvent

查询返回以下输出:

where balance = SUM(pod.Quantity) + SUM(iob.OpeningBalance)

但它应该是

ItemName   Balance
------------------
Item1        35

查询:

ItemName   Balance
------------------
Item1         25

SELECT i.ItemName, SUM(pod.Quantity) + SUM(iob.OpeningBalance) AS Balance FROM dbo.Items i LEFT JOIN dbo.PurchaseOrderDetails pod ON i.ItemID = pod.ItemID LEFT JOIN ItemOpeningBalances iob ON i.ItemID = iob.ItemID GROUP BY i.ItemName 表:

Items

+--------+----------+ | ItemID | ItemName | +--------+----------+ | 1 | Item1 | +--------+----------+ 表:

ItemOpeningBalances

+-------------------+-----------------+-----------------+ | OpeningBalanceID | ItemID | OpeningBalance | +-------------------+-----------------+-----------------+ | 1 | 1 | 10 | +-------------------+-----------------+-----------------+ 表:

PurchaseOrderDetails

2 个答案:

答案 0 :(得分:2)

您的查询正在为PurchaseOrderDetails的每一行添加期初余额。

更改为在PurchaseOrderDetails上使用子查询

SELECT 
  i.ItemName,
  --SUM(pod.Quantity) + SUM(iob.OpeiningBalance) AS Balance
  (pod.Quantity) + (iob.OpeiningBalance) AS Balance
FROM dbo.Items i
left JOIN 
( -- change to sum it in the sub query
  select ItemId, Quantity  = sum(Quantity)
  from dbo.PurchaseOrderDetails 
  group by ItemId
) pod
  ON i.ItemID = pod.ItemID
  left JOIN ItemOpeningBalances iob
  ON i.ItemID = iob.ItemID
--GROUP BY i.ItemName,
--         i.ItemCode

答案 1 :(得分:0)

试试这个,

SELECT 
  i.ItemName,
  pod.PurQuantity + iob.OpeiningBalance AS Balance
FROM dbo.Items i
OUTER APPLY(SELECT SUM(pod.Quantity) AS PurQuantity 
            FROM dbo.PurchaseOrderDetails p
            WHERE i.ItemID = p.ItemID
            ) as pod
left JOIN ItemOpeningBalances iob
ON i.ItemID = iob.ItemID