我不是SQL专家,我过去使用过它,很少遇到Google无法解决的问题…但是这次我需要询问社区。
我有一个名为“ Transactions”的表的数据库,其数据如下:
ProdNo | Price | TransactionDate | PurchasedBy | etc..... ---------------------------------------------------------- 3STRFLEX | 13.02 | 20162911 | AWC | ..... 3STRFLEX | 15.02 | 20162011 | DWC | ..... 3STRFLEX | 15.02 | 20160101 | AWC | ..... AFTV2 | 35.49 | 20162708 | AWC | ..... AFTV2 | 29.99 | 20160106 | DWC | ..... AFTV2 | 29.99 | 20160205 | AWC | .....
所需的输出是:
ProdNo | Price | TransactionDate ----------------------------------- 3STRFLEX | 13.02 | 20162911 AFTV2 | 35.49 | 20162708
我尝试自己编写一个,最终得到如下SQL:
select t.ProdNo, t.TransactionDate as 'LastPurchaseDate', t.Price from Transactions t inner join ( select ProdNo, max(TransactionDate) as 'LastPurchaseDate' from Transactions WHERE Price > 0 group by ProdNo ) tm on t.ProdNo = tm.ProdNo and LastPurchaseDate = tm.LastPurchaseDate
但是,在我的数据集中,此返回(减少)显示每个产品有多行
ProdNo | LastPurchaseDate | Price 3STRFLX | 20120924 | 0.000000 3STRFLX | 20120924 | 22.000000 3STRFLX | 20150623 | 0.000000 3STRFLX | 20150623 | 1.220000 3STRFLX | 20150623 | 1.222197
因此,请确认:无论价格如何,我希望每种产品的最新购买日期为1行,但是我需要在返回的数据中提供价格。
谢谢
您可以使用CTE和排名功能PARTITION BY:
PARTITION BY
WITH CTE AS ( select t.ProdNo, t.TransactionDate as 'LastPurchaseDate', t.Price, rn = row_number() over (partition by ProdNo order by TransactionDate desc) from Transactions t ) SELECT ProdNo, LastPurchaseDate, Price FROM CTE WHERE RN = 1