我有一个场景,其中包含以下查询:
SELECT
Purchasing.Supplier,
PurchasingParts.Part,
PurchasingParts.Description,
PurchasingParts.CostPerUnit,
PurchasingParts.PurchaseOrderNum,
PurchasingParts.ItemNum
FROM PurchasingParts
INNER JOIN Purchasing ON PurchasingParts.PurchaseOrderNum = Purchasing.PurchaseOrderNum
WHERE Supplier = 'Sup1'
ORDER BY PurchasingParts.PurchaseOrderNum DESC
返回以下结果:
Supplier Part Description CostPerUnit PurchaseOrderNum ItemNum
Sup1 cm-14b NULL 9.99 37163 1
Sup1 cm-13 jkljlkjlk 9.99 37160 1
Sup1 cm-13 jkljlkjlk NULL 37158 1
但是,我想过滤那组结果,以便只显示最近的订单(即最高的PurchaseOrderNum)PER PART(仅在Part属性上执行)。所以在这种情况下,最终结果将是:
Supplier Part Description CostPerUnit PurchaseOrderNum ItemNum
Sup1 cm-14b NULL 9.99 37163 1
Sup1 cm-13 jkljlkjlk 9.99 37160 1
我正在使用SQL Server 2008。
答案 0 :(得分:2)
您可以使用ROW_NUMBER()
:
SELECT t.* FROM (
SELECT
Purchasing.Supplier,
PurchasingParts.Part,
PurchasingParts.Description,
PurchasingParts.CostPerUnit,
PurchasingParts.PurchaseOrderNum,
PurchasingParts.ItemNum,
ROW_NUMBER() OVER(PARTITION BY PurchasingParts.Part ORDER BY PurchasingParts.PurchaseOrderNum DESC) as rnk
FROM PurchasingParts
INNER JOIN Purchasing ON PurchasingParts.PurchaseOrderNum = Purchasing.PurchaseOrderNum
WHERE Supplier = 'Sup1'
) t
WHERE t.rnk = 1
ORDER BY t.PurchaseOrderNum DESC