我已经浏览了其他问题,但无法完全找到我要查找的内容。我有一个 SQL 数据库,其中有一个名为 InventoryAllocations 的表。在表中,我有多个 DocumentID 条目,并且想要检索每个唯一 DocumentID 的最后一个条目。我可以通过这样做只检索一个
SELECT top(1) [UID]
,[RecordStatusID]
,[CreatedDate]
,[CreatedTime]
,[CreatedByID]
,[OperationType]
,[InventoryLocationID]
,[DocumentTypeID]
,[DocumentID]
,[SOJPersonnelID]
,[InventorySerialisedItemID]
,[TransactionQty]
,[TransactionInventoryStatusID]
,[Completed]
,[CreatedByType]
,[RecordTimeStamp]
FROM [CPData].[dbo].[InventoryAllocations]
order by DocumentID desc
但我希望它返回一个包含所有唯一 DocumentID 的列表。希望您能提供帮助。非常感谢汉娜 x
最佳答案
SELECT TOP 1 WITH TIES
[UID]
,[RecordStatusID]
,[CreatedDate]
,[CreatedTime]
,[CreatedByID]
,[OperationType]
,[InventoryLocationID]
,[DocumentTypeID]
,[DocumentID]
,[SOJPersonnelID]
,[InventorySerialisedItemID]
,[TransactionQty]
,[TransactionInventoryStatusID]
,[Completed]
,[CreatedByType]
,[RecordTimeStamp]
FROM
[CPData].[dbo].[InventoryAllocations]
ORDER BY
ROW_NUMBER() OVER(PARTITION BY DocumentID ORDER BY [RecordTimeStamp] DESC);
TOP 1
与此处的 WITH TIES
配合使用。
WITH TIES
表示当 ORDER BY = 1
时,SELECT
会获取此记录(因为 TOP 1
>) 以及所有其他具有 ORDER BY = 1
的内容(因为 WITH TIES
)。
关于SQL 为每个组选择前 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722276/