我有一张桌子OrderSpecs
。我需要通过OrderSpecs
选择customer ID
中的所有行,但只需按order ID
选择每个订单的最后一次出现(按时间戳)。我还希望我的查询计算它为每个OrderID
找到的出现次数。
这是我的表格(浓缩以仅显示关键信息):
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*
按日期和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
答案 0 :(得分:1)
应该使用SELECT(未经测试)
中的子查询SELECT
ID, CustomerID, EstimateNo, OrderYear, OrderNo, ProductionNo, AddedBy,
AddedDate, SizeLength, SizeWidth, HomeModelID, HomeTypeID, DrawingNo,
CustomerReference, BuildPieces, ProductionPieces, Notes, SpecDocument, OrderID,
(SELECT COUNT(*) FROM OrderSpecs AS os WHERE o.OrderID=os.OrderID) as [Count]
FROM
OrderSpecs AS o
WHERE
(AddedDate = (SELECT MAX(AddedDate) AS Expr1
FROM OrderSpecs AS i
WHERE (o.OrderID = OrderID)))
AND (CustomerID = @CustomerID)