WITH Invoice AS
(
SELECT E.Id AS ItemCode, C.Id AS WhsCode, SUM(D.Quantity) AS [QtyToMove]
FROM TrxTransaction A
INNER JOIN RepIntegrationLog B ON A.TransactionKey = B.SourceKey
INNER JOIN TrxTransactionSaleItem D ON A.TransactionKey = D.TransactionKey
INNER JOIN InvWarehouse C ON D.WarehouseKey = C.WarehouseKey
INNER JOIN InvProduct E ON D.ProductKey = E.ProductKey
WHERE B.Status = 1 AND B.SourceType = 143
GROUP BY E.Id , C.Id
)
SELECT A.ItemCode, A.WhsCode, A.QtyToMove , OITW.OnHand [SAP QTY], A.QtyToMove - OITW.OnHand AS [Variance]
FROM Invoice A
LEFT OUTER JOIN Colio ..OITW AS OITW ON A.ItemCode = OITW.ItemCode collate SQL_Latin1_General_CP850_CI_AS
AND A.WhsCode = OITW.WhsCode collate SQL_Latin1_General_CP850_CI_AS
WHERE A.QtyToMove > OITW.OnHand