I have a History Table in SQL Server that basically tracks an item through a process. The item has some fixed fields that don’t change throughout the process, but has a few other fields including status and Id which increment as the steps of the process increase.
Basically I want to retrieve the last step for each item given a Batch Reference. So if I do a
Select * from HistoryTable where BatchRef = @BatchRef
It will return all the steps for all the items in the batch – eg
Id Status BatchRef ItemCount 1 1 Batch001 100 1 2 Batch001 110 2 1 Batch001 60 2 2 Batch001 100
But what I really want is:
Id Status BatchRef ItemCount 1 2 Batch001 110 2 2 Batch001 100
Edit: Appologies – can’t seem to get the TABLE tags to work with Markdown – followed the help to the letter, and looks fine in the preview
It’s kind of hard to make sense of your table design – I think SO ate your delimiters.
The basic way of handling this is to GROUP BY your fixed fields, and select a MAX (or MIN) for some unqiue value (a datetime usually works well). In your case, I think that the GROUP BY would be BatchRef and ItemCount, and Id will be your unique column.
Then, join back to the table to get all columns. Something like: