【问题标题】:SQL Server - Product and their latest information required from history tableSQL Server - 历史表中所需的产品及其最新信息
【发布时间】:2017-07-23 11:25:12
【问题描述】:

我有一个Products 表,其中包含以下列

ProductId - INT - PK
Name - Varchar
Price Decimal

我还有一张桌子ProductPriceHistory

当产品价格更新时,我使用触发器将旧价格和新价格存储在该表中。此表有以下列

ProductPriceHistoryId
Name
OldPrice
NewPrice
UpdateDate

我可以根据Name 列加入此表。

现在的问题是,在我的结果集中 - 我想获得 Product.NameProduct.Price 和(用于获取表 ProductPriceHistory 中的最后更新值)ProductPriceHistory.NewPrice

挑战在于,在历史表中,我根据不同的日期为每个产品有很多行。对于每个产品,我需要从为该产品存储的最新行中获取信息。

【问题讨论】:

    标签: sql stored-procedures ranking


    【解决方案1】:

    您应该将 ProductId 存储在历史表中,因为它是唯一的,然后根据该值连接表。

    然后,按日期降序排列查询,限制为 1(或 Select Top 1 fields From...)。这只会为您提供最新的更新。

    编辑:您的表结构未标准化。对我来说,您的表格更有意义:

    Products:
    ProductId
    Name
    Description
    
    Prices:
    ProductId
    Price
    UpdateDate
    

    那么您的查询将是:

     SELECT TOP 1 Products.ProductId, Products.Name, Prices.Price, Prices.UpdateDate FROM etc
    

    【讨论】:

    • 限制查询返回的行数不是标准 sql,它的可用性取决于 dbms。
    • 编辑为包括“选择顶部...”
    【解决方案2】:

    执行此操作的标准 SQL 方法是将历史表与自身的聚合连接起来,在该聚合中,您为每个产品取最大日期。

    select  t1.Name, t1.Price, t2.NewPrice
    from    Products t1
    join    ProductPriceHistory t2
    on      t1.Name = t2.name
    join    (
              select  Name, max(UpdateDate) as MaxDate
              from    ProductPriceHistory
              group by Name
            ) t3
    on      t2.Name = t3.Name and t2.UpdateDate = t3.MaxDate
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-30
      • 2020-09-22
      • 1970-01-01
      • 2017-01-17
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多