我有一个查询,希望它列出每个库存项目的所有最新交易价格。我尝试使用MAX()
列出每个商品的所有最新交易,但不包括价格,它可以工作,但是当我包括价格时,该方法将不起作用。
这是我的查询
SELECT MAX(DocDate) AS DocDate, StockCode, Price
FROM StockPurchasePriceHistory spph
INNER JOIN Stocks s
ON spph.Stock = s.Id
GROUP BY StockCode, Price
ORDER BY StockCode ASC
输出
答案 0 :(得分:1)
使用row_number
select * from (SELECT row_number()over(partition by StockCode order by DocDate desc) rn
, StockCode, Price
FROM StockPurchasePriceHistory spph
INNER JOIN Stocks s
ON spph.Stock = s.Id
) a where a.rn=1
答案 1 :(得分:0)
尝试一下:
SELECT MAX(DocDate) AS DocDate, StockCode, sum(Price) as Price
FROM StockPurchasePriceHistory spph
INNER JOIN Stocks s
ON spph.Stock = s.Id
GROUP BY StockCode
ORDER BY StockCode ASC
答案 2 :(得分:0)
这是使用APPLY
的好地方:
SELECT spph.DocDate, s.StockCode, spph.Price
FROM Stocks s CROSS APPLY
(SELECT TOP (1) spph.*
FROM StockPurchasePriceHistory spph
WHERE spph.Stock = s.Id
ORDER BY spph.DocDate DESC
) spph;
有了StockPurchasePriceHistory(Stock, DocDate desc)
上的索引,我希望它会比使用窗口函数的替代方法快一点,并且与相关子查询的速度差不多。