Microsoft访问子查询

时间:2014-03-20 17:35:19

标签: ms-access

  • 产品表:productid,productname
    • Delivered_item:numberorder,productid,qtyordered
    • product_issued:productid,qtyissued

2 个答案:

答案 0 :(得分:1)

SELECT i.itemNo, Sum(d.qtyordered) AS SumOfqtyordered, 
Sum(iss.qtyissued) AS SumOfqtyissued, 
Sum(r.qtyreturn) AS SumOfqtyreturn, 
(Sum(d.qtyordered)-Sum(iss.qtyissued)+Sum(r.qtyreturn)) AS Balance
FROM item AS i, delivered_item AS d, item_return AS r, item_issued AS iss
WHERE i.itemno=d.itemno 
AND d.itemno=r.itemno
AND iss.itemno=i.itemno
GROUP BY i.itemNo;

语法比较简单,我讨厌Joins中的select语句

修改

抱歉,我没有意识到你有一对多的关系

SELECT i.itemNo, TotalOrdered, TotalReturned, TotalIssued,       
(TotalOrdered - TotalIssued + TotalReturned) as Balance
FROM (( item i
INNER JOIN
(   SELECT itemno,          Sum(qtyordered) as TotalOrdered
   FROM delivered_item
   GROUP BY itemno
) as d ON d.itemno = i.itemno)
INNER JOIN
(   SELECT itemno,          Sum(qtyreturn) as TotalReturned
   FROM item_return
   GROUP BY itemno
) as r ON d.itemno = r.itemno)
INNER JOIN
(   SELECT itemno,          Sum(qtyissued) as TotalIssued
   FROM item_issued
   GROUP BY itemno
) as iss ON iss.itemno = i.itemno

这是另一个答案的代码,修复了MS Access' sql格式,没有语法错误并经过测试

<强> EDIT2

如果您希望产品展示,即使它不在所有表中,也使用LEFT连接:

SELECT i.itemNo, Nz(TotalOrdered,0), Nz(TotalReturned,0), Nz(TotalIssued,0), 
(Nz(TotalOrdered,0)-Nz(TotalIssued,0)+Nz(TotalReturned,0)) AS Balance
FROM ((item AS i 
LEFT JOIN (SELECT itemno, Sum(qtyordered) AS TotalOrdered FROM delivered_item 
GROUP BY itemno)  AS d ON d.itemno=i.itemno)
LEFT JOIN (SELECT itemno, Sum(qtyreturn) AS TotalReturned FROM item_return 
GROUP BY itemno)  AS r ON r.itemno=i.itemno)
LEFT JOIN (SELECT itemno, Sum(qtyissued) AS TotalIssued FROM item_issued 
GROUP BY itemno)  AS iss ON iss.itemno=i.itemno;

答案 1 :(得分:0)

SELECT itemNo, TotalOrdered, TotalReturned, TotalIssued,
       (TotalOrdered - TotalIssued + TotalReturned) Balance
FROM item i
INNER JOIN
(
   SELECT itemno,
          Sum(qtyordered) TotalOrdered
   FROM delivered_item
   GROUP BY itemno
) d ON d.itemno = i.itemno
INNER JOIN
(
   SELECT itemno,
          Sum(qtyreturned) TotalReturned
   FROM item_return
   GROUP BY itemno
) r ON d.itemno = r.itemno
INNER JOIN
(
   SELECT itemno,
          Sum(qtyissued) TotalIssued
   FROM item_issued
   GROUP BY itemno
) iss ON iss.itemno = i.itemno