I am working on a SQL statement with SQL Server. I am left joining the main select statement with a sub select statement, to get the value from sub select statement, and when there's no matching value in sub select statement, it returns the value from main select statement.
This is my SQL:
SELECT
OIVL.ItemCode, OIVL.BASE_REF, ISNULL(A.OrigLine, OIVL.DocLineNum)
FROM
OIVL
LEFT JOIN
(SELECT DISTINCT
IPF1.OrigLine, OIPF.DocNum, IPF1.BaseEntry, IPF1.Reference,
IPF1.ItemCode, IBT1.BatchNum
FROM
IPF1
LEFT JOIN
OIPF ON IPF1.DocEntry = OIPF.DocEntry
LEFT JOIN
IBT1 ON IPF1.BaseEntry = IBT1.BaseEntry
AND IPF1.ItemCode = IBT1.ItemCode
AND IPF1.OrigLine = IBT1.BaseLinNum) A ON OIVL.BASE_REF = A.DocNum
AND OIVL.ItemCode = A.ItemCode
AND OIVL.DocLineNum = A.OrigLine
I've checked the result of sub select statement, it returns correct result - same item code on line 5 and 7.
But the result is returning OIVL.DocLineNum
while A.OrigLine
has value.