我有一张桌子OrderSpecs
。我需要从 a 中选择所有行,但仅OrderSpecs
通过 acustomer ID
选择每个订单的最后一次出现(按时间戳)order ID
。我还希望我的查询计算它为每个OrderID
.
这是我的表格(浓缩为仅显示关键信息):
订单规格
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*
按日期和选择最近的订单行时,我的查询工作正常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)
但是,我无法弄清楚如何计算每个OrderID
.
例如,我希望我的输出表是这样的(搜索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