I have a table OrderSpecs. I need to select all of the rows from OrderSpecs by a customer ID, but only selecting the last occurrence (by a time stamp) of each order by an order ID. I would also like my query to count the number of occurrences it found for each OrderID.
Here is my table (condensed to show only the key information):
OrderSpecs
ID OrderID CustomerID CreatedDate SpecDocument
1 1 5 01/08/2012 11:00:00 *Amendment1*
2 1 5 02/08/2012 15:32:41 *Amendment2*
3 2 31 04/08/2012 16:19:00 *Amendment1*
4 3 5 05/08/2012 12:10:12 *Amendment1*
5 4 10 08/08/2012 09:32:56 *Amendment1*
6 1 5 09/08/2012 11:47:02 *Amendment3*
My query works fine when selecting the most recent order rows by date and CustomerID:
SELECT
ID, CustomerID, EstimateNo, OrderYear, OrderNo, ProductionNo, AddedBy,
AddedDate, SizeLength, SizeWidth, HomeModelID, HomeTypeID, DrawingNo,
CustomerReference, BuildPieces, ProductionPieces, Notes, SpecDocument, OrderID
FROM
OrderSpecs AS o
WHERE
(AddedDate = (SELECT MAX(AddedDate) AS Expr1
FROM OrderSpecs AS i
WHERE (o.OrderID = OrderID)))
AND (CustomerID = @CustomerID)
However, I am unable to work out how to count the number of a occourances there are for each OrderID.
For example, I would like my output table to be like this (searching by CustomerID = 5):
ID OrderID CustomerID CreatedDate SpecDocument Count
6 1 5 09/08/2012 11:47:02 *Amendment3* 3
4 3 5 05/08/2012 12:10:12 *Amendment1* 1
Should work with a sub-query in the SELECT (untested)