Your have a couple of problems. One syntax error is that the inner query is aggregating by maxdate
, and then there are others. That is unnecessary. The logical problem is that you need to use the date in the on
clause:
SELECT ri.*
FROM [Rigid Industries$Item Ledger Entry] ri INNER JOIN
(SELECT [Item No_], MAX([Posting Date]) AS maxDate
FROM [Rigid Industries$Item Ledger Entry]
WHERE [Posting Date] <= CONVERT(datetime, '2014-01-17 02:33:16.939')
GROUP BY [Item No_]]
) itDat
ON ri.[Item No_] = itDat.[Item No_] and
ri.[Posting Date] = itDat.maxDate
WHERE ri.[Quantity] > 0
ORDER BY ri.[Location Code] DESC, ri.[Item No_] ASC, ri.[Posting Date] DESC;
An alternative way of writing this type of query is to use a not exists
clause along with an index on [Rigid Industries$Item Ledger Entry]([Item No_], [Posting Date])
:
SELECT ri.*
FROM [Rigid Industries$Item Ledger Entry] ri
WHERE ri.[Quantity] > 0 AND
NOT EXISTS (SELECT 1
FROM [Rigid Industries$Item Ledger Entry] ri2
WHERE ri2.[Item No_] = ri.[Item No_] AND
ri2.[Posting Date] > ri.[Posting Date]
)
ORDER BY ri.[Location Code] DESC, ri.[Item No_] ASC, ri.[Posting Date] DESC;
What this is saying is: "Get me all the rows from that table with the too long and complicated name such that there are no other rows in the table with the same item number and a bigger posting date."