2012-01-19 70 views
0

我有一個表(Inventory_Line),其中蓋子是自動遞增和IID是一個單一的數字指的是盤點日期,PID是一個數字組成#。我們使用這個表格來存貨。多個SQL查詢類同場

LID IID NAME PID QTY 
--- --- ------ --- --- 
1 1 Part A 213 12 
2 1 Part B 200 15 
3 2 Part A 213 9 
4 2 Part B 200 7 

我們也有一個表ORDER_LINE

OLID OID NAME PID QTY 
---- --- ------ --- --- 
1  217 Part A 213 12 
2  217 Part B 200 15 
3  218 Part A 213 9 
4  218 Part B 200 7 

我的目標是展示

((Previous Inventory Qty (Inventory_Line.IID=1)) AS PREV_INV + 
(ORDERED Qty (Order_Line.OID = 217 AND 218)) AS ORDERED - 
(Current Inventory Qty Inventory_Line.IID=2) AS CURRENT_INV) AS SOLD 
WHERE PID = X 

輸出會是這樣的:

PID NAME PREV_INV ORDERED CURRENT_INV SOLD 
--- ------ -------- ------- ----------- ---- 
213 Part A 12  21  9   24 

我們正在使用MS訪問和我有一些經驗加入,但我有點卡住如何取消這一點。任何幫助,將不勝感激。

+0

@HansUP加入示例我會考慮正確的輸出到原來的帖子 –

回答

1

你在想這些問題嗎?

SELECT t.pid, 
     Nz([pi].[qty], 0) + Nz([o].[qty], 0) - Nz([s].[qty], 0) AS dat 
FROM (((SELECT DISTINCT pid 
     FROM inventory_line) AS t 
     LEFT JOIN (SELECT * 
        FROM inventory_line 
        WHERE iid = 2) AS pi 
      ON t.pid = pi.pid) 
     LEFT JOIN (SELECT * 
        FROM inventory_line 
        WHERE iid = 3) AS s 
      ON t.pid = s.pid) 
     LEFT JOIN (SELECT * 
        FROM order_line 
        WHERE oid = 217 
          OR oid = 218) AS o 
     ON t.pid = o.pid 
WHERE (((t.pid) = [Enter:])) 

上面需要一些工作,但是應該做的事情會更清晰,在輸出期望更多的輸入。


回覆評論

SELECT t.pid, 
     t.name, 
     pi.qty, 
     o.q, 
     s.qty, 
     Nz([pi].[qty]) + Nz([o].[q]) - Nz([s].[Qty]) AS sold 
FROM (((SELECT DISTINCT pid, 
         [Name] 
     FROM inventory_line) AS t 
     LEFT JOIN (SELECT pid, 
          qty 
        FROM inventory_line 
        WHERE iid = 1) AS pi 
      ON t.pid = pi.pid) 
     LEFT JOIN (SELECT pid, 
          qty 
        FROM inventory_line 
        WHERE iid = 2) AS s 
      ON t.pid = s.pid) 
     LEFT JOIN (SELECT pid, 
         SUM(qty) AS q 
        FROM order_line 
        WHERE oid = 217 
          OR oid = 218 
        GROUP BY pid) AS o 
     ON t.pid = o.pid 
WHERE (((t.pid) = [Enter:])) 
+0

那麼從閱讀這個SQL的查詢將基於一個輸入的PID,我想要的是所有PID的完整列表,所以也許我會省略最後一個林e並嘗試測試。這很多我知道這比SQl明智的經驗更復雜。 –

+0

如果有幫助,我在原始帖子中添加了期望的輸出示例。 –

+0

我又增加了一個例子。 – Fionnuala

0

我不能制定出在哪裏售出列來源於但這裏的24是用於其餘

另一種解決方案
SELECT Order_Line.PID, Order_Line.NAME, DLookUp("[QTY]","[Order_Line]","[OID]=" & [OID]-1 & " AND PID=" & [PID]) AS PREV_INV, DSum("[QTY]","[Order_Line]","[PID]=" & [PID]) AS ORDERED, Order_Line.QTY AS CURRENT_INV FROM Order_Line;