Max()未过滤掉MIN()

时间:2018-06-29 17:42:20

标签: sql sql-server sql-server-2008

当我使用下面的查询运行时,它返回重复的StockNo,因为其中一些重复的WorkInProgress代码(FiWipStatus代码)。 有没有一种方法可以基于基于rowlastupdated的MIN()排除记录? 一如既往,感谢您的帮助!

SELECT     dbo.InventoryVehicle.StockNo, dbo.VehicleSales.FiWipStatusCode, 
MAX(dbo.VehicleSales.RowLastUpdated) AS Expr1
FROM         dbo.VehicleSales RIGHT OUTER JOIN
dbo.InventoryVehicle ON dbo.VehicleSales.StockNo = dbo.InventoryVehicle.StockNo
GROUP BY dbo.InventoryVehicle.StockNo, dbo.VehicleSales.FiWipStatusCode, 
dbo.VehicleSales.RowLastUpdated

1 个答案:

答案 0 :(得分:2)

如果我正确理解它,则需要根据它们的上次更新日期和时间(即RowLastUpdated)来获取记录。如果是这样,您可以执行以下操作:

SELECT 
    iv.StockNo
,   vs.FiWipStatusCode
,   vs.RowLastUpdated 
FROM (
SELECT     
    iv.StockNo
,   vs.FiWipStatusCode
,   vs.RowLastUpdated 
,   ROW_NUMBER() OVER(PARTITION BY iv.StockNo ORDER BY vs.RowLastUpdated DESC) AS RN
FROM         
    VehicleSales vs
LEFT JOIN  InventoryVehicle iv ON vs.StockNo = iv.StockNo   
) D 
WHERE 
    RN = 1

其中ROW_NUMBER()将根据StockNo对行进行编号,并根据DESC中的RowLastUpdated对其进行排序。因此,每个不同的StockNo的第一行将是聚合查询中的MAX()日期时间。如果要获取MIN(),只需将顺序更改为ASC