Microsoft访问查询设计

时间:2014-03-19 15:56:05

标签: sql ms-access

SELECT 
    Item.Itemno 
    , SUM(Delivered_item.qtyordered) AS SumOfqtyordered 
    , SUM(Item_issued.qtyissued) AS SumOfqtyissued
FROM  
    Item  
    INNER JOIN Delivered_item ON Item.Itemno = Delivered_item.itemno 
    INNER JOIN Item_issued ON Item.Itemno = Item_issued.Itemno
GROUP BY  
    Item.Itemno;

这是我的sql视图。在我的数据库中,delivered_item有7条记录,而item_issued只有2条记录。当我执行SUM时,qtyissued的总数出错,1条记录(qtyissued)乘以3而另一条记录乘以4,因为delivered_item有7条记录(2个相同itemno)...如何解决这个问题...

1 个答案:

答案 0 :(得分:0)

您需要使用子查询:

SELECT *
FROM item i
INNER JOIN
  (SELECT itemno,
          Sum(qtyordered)
   FROM delivereditem
   GROUP BY itemno) d ON d.itemno = i.itemno
INNER JOIN
  (SELECT itemno,
          Sum(qtyissued)
   FROM itemissued
   GROUP BY itemno) iss ON iss.itemno = i.itemno

如果您认为可能需要执行此操作,请将每个子查询转换为视图并使用该子查询(保存打字时)

编辑:在子查询中添加了分组。对不起!