代码之家  ›  专栏  ›  技术社区  ›  Gratzy

在WHERE子句中使用select max()函数改进SQL查询

  •  3
  • Gratzy  · 技术社区  · 15 年前

    此查询的目的是将产品及其在售产品的价格收回,价格应自最近的日期开始,但不等于传入的日期,基本上是最新的可用价格。没有每天的价格记录。在where子句中使用aggregate select语句有点错误。有更好的方法吗?可能在连接条件中?

            select  
            p.ProductName,
            pp.Price,
            pp.Date,
            from product p
            inner join productprice pp  on p.productid = pp.productid
            where 
            pp.evaluationdate = (select  max(Date) from productprice 
                                 where productid = p.productid  
                                 and date < @DateIn) 
            and p.producttype = 'OnSale'
    

    实际上查询有点复杂,但这本质上就是问题所在。谢谢你的意见。

    编辑 将有多个产品返回

    编辑 我正在试验@remus rusanu'和@km的建议(尽管@remus rusanu删除了他的建议),这三个建议,包括我的原始建议,在性能方面似乎都差不多。我正试图决定一个人是否以某种无形的方式,如维护、自我记录等,为其他人维护,提供了一种优于其他人的利益。再次感谢。

    3 回复  |  直到 15 年前
        1
  •  5
  •   Community Stefan Steinegger    7 年前

    ;WITH CurrentPrice AS 
    (
    SELECT productid,max(Date) AS Date
        FROM productprice 
        WHERE date < @DateIn 
        GROUP BY productid
    )
    
    select  
        p.ProductName,
        pp.Price,
        pp.Date,
        from product p
            inner join CurrentPrice pa  on p.productid = pa.productid
            inner join productprice pp  on pa.productid = pp.productid AND pa.Date=pp.Date
        where p.producttype = 'OnSale'
    

    derived table version from @Remus Rusanu

    productprice OnSale

    ;WITH CurrentPrice AS 
    (
    select  
        p.productid,
        MAX(pp.Date) AS Date
        from product p
            inner join productprice pp  on pa.productid = pp.productid
        where p.producttype = 'OnSale' AND pp.date < @DateIn 
        GROUP BY productid
    )
    select  
        p.ProductName,
        pp.Price,
        pp.Date,
        from CurrentPrice           pa
            inner join product      p   on pa.productid = p.productid
            inner join productprice pp  on pa.productid = pp.productid AND pa.Date=pp.Date
        where p.producttype = 'OnSale'
    
        2
  •  1
  •   Damon    15 年前

        SELECT * FROM (select  
                p.ProductName,
                pp.Price,
                pp.Date,
                RANK() OVER(PARTITION BY p.ProductId ORDER BY pp.Date DESC) as row_rank
                from product p
                  join productprice pp  on p.productid = pp.productid
                where 
                  pp.date < @DateIn
                  and p.producttype = 'OnSale'
        ) saleprice
        where row_rank = 1
    

        3
  •  0
  •   atfergs    15 年前
    SELECT TOP 1 p.ProductName, pp.Price, pp.Date,
    FROM product p
    INNER JOIN productprice pp on ...
    WHERE pp.date < @DateIn
    ORDER BY pp.date DESC