Made this re-write as suggested:
Code:
SELECT P.ID, P.QTY, T_DATE
FROM PARTS P
INNER JOIN INVENTORY I
ON P.ID = I.PART_ID
WHERE P.QTY > 0
AND I.CODE = ‘R’
AND I.T_DATE = (SELECT MAX(Z.T_DATE)
FROM INVENTORY Z
WHERE Z.PART_ID = P.ID
AND Z.T_DATE < DATEADD(MONTH,-12,GETDATE()))
ORDER BY P.ID
The statement is still off.
My data has this:
part qty date
AB1 7 12/22/2011 (has earlier dates, but significant is today's date 1 year ago)
AB1 7 12/22/2011
AB1 7 12/22/2011
AB1 7 12/22/2011
AB1 7 3/19/2012
AB1 7 3/19/2012
AB1 7 4/9/2012
AB1 7 4/9/2012 ...
AB1 7 9/17/2012 (latest/Max date)
Part AB1 is being returned when it should not.
Funny thing is that some of the other parts that previously were being incorrectly pulled into the recordset, are now not.
I think that because the record contained today's date - 2011, it somehow got pulled in.
As a test, I can see that MAX(T_DATE) is being returned, but this piece, "AND Z.T_DATE < DATEADD(MONTH,-12,GETDATE()))", is where it goes wrong.
PS: also tried not greater than: z.t_date !> dateadd etc....