Hi all and thanks for the assistance ...
I'm trying to (logically) combine to tables for a total inventory count, then subtract items from a third table.
I UNION two tables as such:
that code works well and I get the proper totals per POLineID.
I have the table that I should use for subtracting as
this always works on its own properly grouping by POLineID
Now I want to take the qtyIN - qtyOut for a total result. What I'm doing (full code) is:
but the results don't work.
It is applying the subtraction multiple times, not on the aggregate results.
Can you tell me what I'm missing? I didn't want to just through in a DISTINCT without knowing.
Many thanks,
Mark
I'm trying to (logically) combine to tables for a total inventory count, then subtract items from a third table.
I UNION two tables as such:
Code:
/* Inventory Purchased Afloat */
SELECT unitQty AS qtyIn, POLineID
FROM dbo.tblPOLine AS po
WHERE (locationID = 6)
UNION
/* Inventory Purchased At Orgin Shipped */
SELECT tr.qty AS qtyIn, tr.POLineID
FROM dbo.tblTRLine AS tr LEFT OUTER JOIN
dbo.tblTRLedger AS trL ON tr.TRLedgerID = trL.TRLedgerID
WHERE (trL.locationID = 6)
that code works well and I get the proper totals per POLineID.
I have the table that I should use for subtracting as
Code:
/* All Landed Inventory */
SELECT tr.POLineID, SUM(tr.qty) AS qtyOut
FROM dbo.tblTRLine AS tr LEFT OUTER JOIN
dbo.tblTRLedger AS trL
ON tr.TRLedgerID = trL.TRLedgerID
WHERE (trL.locationID = 3) OR (trL.locationID = 4)
GROUP BY tr.POLineID
this always works on its own properly grouping by POLineID
Now I want to take the qtyIN - qtyOut for a total result. What I'm doing (full code) is:
Code:
/********************************/
/******* Inventory Afloat *******/
/********************************/
/* */
/* */
/* Inventory Purchased Afloat */
/********************************/
WITH InvAtSea AS
(
/* Inventory Purchased Afloat */
SELECT unitQty AS qtyIn, POLineID
FROM dbo.tblPOLine AS po
WHERE (locationID = 6)
UNION
/* Inventory Purchased At Orgin Shipped */
SELECT tr.qty AS qtyIn, tr.POLineID
FROM dbo.tblTRLine AS tr LEFT OUTER JOIN
dbo.tblTRLedger AS trL ON tr.TRLedgerID = trL.TRLedgerID
WHERE (trL.locationID = 6)
),
/* All Landed Inventory */
InvLanded AS
(
SELECT tr.POLineID, SUM(tr.qty) AS qtyOut
FROM dbo.tblTRLine AS tr LEFT OUTER JOIN
dbo.tblTRLedger AS trL
ON tr.TRLedgerID = trL.TRLedgerID
WHERE (trL.locationID = 3) OR (trL.locationID = 4)
GROUP BY tr.POLineID
)
SELECT ino.qtyIn - ISNULL(out.qtyOut, 0) as qtyAtSea
FROM InvAtSea AS ino
LEFT OUTER JOIN
InvLanded AS out
ON ino.POLineID = out.POLineID
but the results don't work.
It is applying the subtraction multiple times, not on the aggregate results.
Can you tell me what I'm missing? I didn't want to just through in a DISTINCT without knowing.
Many thanks,
Mark