我有一张名为'Purchases'的表:
PurchaseID,PurchaseDate,Vendor
╔════════════╦══════════════╦════════╗
║ PurchaseID ║ PurchaseDate ║ Vendor ║
╠════════════╬══════════════╬════════╣
║ 1 ║ 01 jan 2013 ║ XYZ ║
║ 2 ║ 02 jan 2013 ║ ABC ║
╚════════════╩══════════════╩════════╝
和使用PurchaseID密钥链接的表'PurchaseDetails':
DetailID,PurchaseID,ProductCode,Price
╔══════════╦════════════╦═════════════╦═══════╗
║ DetailID ║ PurchaseID ║ ProductCode ║ Price ║
╠══════════╬════════════╬═════════════╬═══════╣
║ 1 ║ 1 ║ 001 ║ 2.34 ║
║ 2 ║ 1 ║ 002 ║ 3.75 ║
║ 3 ║ 2 ║ 001 ║ 5.93 ║
║ 4 ║ 2 ║ 002 ║ 8.14 ║
╚══════════╩════════════╩═════════════╩═══════╝
我想获得给定ProductCode的最后一个PurchaseDate的价格和供应商。
例如: 如果ProductCode是'001',那么我希望查询返回: 5.93 | ABC
我尝试过使用带有DESC ORDER BY的TOP 1 SELECT,但是我无法让JOIN部分工作。
答案 0 :(得分:1)
使用TOP1方法,以下查询应该可以正常工作
SELECT Vendor, Price
FROM Purchases p
INNER JOIN PurchaseDetails pd on pd.PurchaseID=p.PurchaseID
WHERE PurchaseID = (SELECT TOP 1 PurchaseID FROM Purchases WHERE DetailID = DetailID ORDER BY PurchaseDate DESC)
您也可以使用Row_Number over来实现此
答案 1 :(得分:0)
这是我的解决方案:
SELECT TOP 1 Purchases.Vendor, Purchases.PurchaseDate, PurchaseDetails.Price FROM PurchaseDetails INNER JOIN Purchases
ON PurchaseDetails.PurchaseID=Purchases.PurchaseID WHERE PurchaseDetails.ProductCode='001' ORDER BY Purchases.PurchaseDate DESC
答案 2 :(得分:0)
由于您使用的是SQL Server 2005+,因此可以使用窗口函数来获取结果。在这种情况下,我使用了row_number()
:
select vendor, price
from
(
select p.purchaseId, p.purchaseDate, p.vendor,
d.productCode, d.price,
row_number() over(partition by d.productCode order by p.purchaseDate desc) seq
from purchases p
inner join purchaseDetails d
on p.purchaseId = d.purchaseId
) src
where seq = 1;