I have the following query which is returning 4 results when the table FI_CurrentReceiptData only has 2 rows. The extra rows are exact duplicates. I can use DISTINCT to fix, but my understanding is that this is bad practice and I would do better to find and correct the error (IS THIS CORRECT?).
Why is this query doubling the results?
All variables are declared elsewhere in a stored procedure and this query does return the needed fields.
SELECT ( (Select Max(ReceiptNumber)
from Avanti_InventoryReceipts) + CR.Seq ),
CR.ItemNumber,
Convert(char(8), GETDATE(), 112),
PONum,
'FL-INV',
PH.POVendor,
0,
0,
'O',
CR.QtyOrdered,
QtyReceivedToday,
QtyReceivedToday,
Case @closePO
When 'N' Then Case
When ( QtyOrdered - QtyReceivedToday ) < 0 Then 0
Else ( QtyOrdered - QtyReceivedToday )
End
When 'Y' Then 0
Else 0
End,
PD.TransCost * QtyReceivedToday,
IH.PriceWholeSale,
IH.CostLast,
QtyReceivedToday,
0,
'',
PODetailDescription /* , .... More columns...*/
FROM FI_CurrentReceiptData CR
LEFT JOIN Avanti_PODetails PD
ON CR.PONum = PD.PONumber
LEFT JOIN Avanti_POHeader PH
ON CR.PONum = PH.PONumber
LEFT JOIN Avanti_InventoryHeader IH
ON CR.ItemNumber = IH.ItemNumber
NEW WHERE CLAUSE SOLUTION:
FROM FI_CurrentReceiptData CR
inner JOIN Avanti_PODetails PD ON CR.PONum = PD.PONumber AND CR.ItemNumber = PD.TransItem AND CR.QtyOrdered = PD.TransQty
left JOIN Avanti_POHeader PH ON PD.PONumber = PH.PONumber
left JOIN Avanti_InventoryHeader IH ON CR.ItemNumber = IH.ItemNumber
One of the joined tables has more than one matching row.
I cannot say for certain which one, but if I were you I’d start looking
at the Avanti_PODetails table. Does it have more than one matching record for any of the two receipts?