Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Consulta SQL para obter os preços mais recentes, dependendo da data


O mais fácil seria usar um CTE com ROW_NUMBER função:
WITH CTE AS
(
  SELECT dbo.twProducts.title, dbo.LowestPrices.productAsin, dbo.twProducts.sku, 
       dbo.LowestPrices.tweAmzPrice, dbo.LowestPrices.price, dbo.LowestPrices.priceDate,
       RN = ROW_NUMBER()OVER( PARTITION BY productAsin ORDER BY priceDate DESC)
  FROM   dbo.aboProducts INNER JOIN
       dbo.LowestPrices ON dbo.aboProducts.asin = dbo.LowestPrices.productAsin 
       INNER JOIN dbo.twProducts ON dbo.aboProducts.sku = dbo.twProducts.sku
)
SELECT * FROM CTE WHERE RN = 1