[英]SQL select last occurrence of row & count number of occurrences
I have a table OrderSpecs
. 我有一张表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
. 我需要通过customer ID
从OrderSpecs
选择所有行,但只需按order ID
每个订单的最后一次出现(按时间戳)。 I would also like my query to count the number of occurrences it found for each OrderID
. 我还希望我的查询计算它为每个OrderID
找到的出现次数。
Here is my table (condensed to show only the key information): 这是我的表(浓缩以仅显示关键信息):
OrderSpecs 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
: 按日期和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
. 但是,我无法确定如何计算每个OrderID
的遮挡数量。
For example, I would like my output table to be like this (searching by CustomerID = 5
): 例如,我希望我的输出表是这样的(按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) 应该使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.