SQL查询帮助:选择最新记录并加入另一个表

时间:2013-01-01 00:09:43

标签: sql

我一直在努力尝试在SQL Server 2012中编写一个可在此处运行的查询,但没有成功。

我有tblProducts看起来像这样,有大约100000行:

SKU, Title, CategoryID
155, 'Product a', 5
176, 'Product b', 5
630, 'Product 1', 10

和tblPrices看起来像这样并且有大约一百万行,每行记录特定时间项目的价格和库存:

SKU, Price, StockCount, TimeStamp (smalldatetime)
155, 10, 5, 2012-12-31 23:40:00
155, 9, 6, 2012-12-30 23:40:00
155, 7, 6, 2012-12-29 21:40:00
176, 0.50, 0, 2012-12-31 23:40:00

基本上,我想获得类别5中的SKU列表,其当前价格是> 3。

到目前为止,我已经:

SELECT *
FROM tblPrices
WHERE Timestamp IN (
    SELECT MAX(TimeStamp)
    FROM tblPrices
    GROUP BY SKU

给出了tblPrices中每个SKU的当前/最新价格:

SKU, Price, StockCount, TimeStamp
155, 10, 5, 2012-12-31 23:40:00
176, 0.50, 0, 2012-12-31 23:40:00

但我真正需要的是按价格过滤此表格,将其加入tblProducts,然后按类别过滤。但是,无论我怎么做,它都会为每个SKU返回几行或忽略价格条件。以下返回多个SKU(因此缺少最新价格的点必须> 3)并且还需要大约2分钟来执行并返回810行,其中大约四分之一是唯一的:

SELECT tblProducts.SKU , CategoryID
FROM tblProducts,

(SELECT EAN, Price
FROM tblPrices
WHERE Timestamp IN (
    SELECT MAX(TimeStamp)
    FROM tblPrices
    GROUP BY SKU
)) a

WHERE tblProducts.EAN = a.EAN AND tblProducts.CategoryID=5 AND a.Price > 3

我真的很感激任何帮助,因为我自己无处可去。

3 个答案:

答案 0 :(得分:2)

WHERE子句中使用子查询

SELECT SKU
FROM tblProducts
WHERE CategoryId = 5 AND SKU IN (
    SELECT SKU
    FROM tblPrices
    WHERE Price > 3 AND Timestamp IN (
        SELECT MAX(TimeStamp)
        FROM tblPrices
        GROUP BY SKU
    )
)

答案 1 :(得分:1)

您可以在PARTITION BY SKUORDER BY TimeStamp DESC的CTE中使用ROW_NUMBER,只为CATEGORYID=5的每个SKU获得一行:

WITH CTE AS 
(
   SELECT 
      PR.SKU, PR.Price, PR.StockCount, PR.TimeStamp, P.Title, P.CategoryID,
      ROW_NUMBER() OVER (PARTITION BY PR.SKU ORDER BY PR.TimeStamp DESC) AS RN
   FROM 
      tblProducts P 
      INNER JOIN tblPrices PR ON P.SKU=PR.SKU
   WHERE 
      p.CategoryID=5
      AND PR.Price > 3
)
SELECT 
   SKU, Price, StockCount, TimeStamp, Title, CategoryID
FROM 
   CTE
WHERE 
   RN = 1

CTE就像子查询一样,PARTITION BY类似于GROUP BY

答案 2 :(得分:0)

与具有相关子查询的Voithos相同。

 SELECT p.SKU, p.Price
 FROM tblPrices p
      Join tblProducts d 
           On d.sku = p.sku
 WHERE d.CategoryId = 5 
     And p.Price > 3
     AND p.Timestamp =
        (Select Max(TimeStamp)
         From tblPrices 
         Where Sku = p.sku)