从重写StartDates中查找StartDate,EndDate

时间:2012-04-02 11:52:00

标签: sql join date-range

我有两个包含以下(简化)结构的表:

  1. 表“因素”,其中包含有关购买商品因素的数据,并包含以下列:

    FactorSerial,PurchaseDate,PurchasedGood

  2. 表格“价格”在不同日期保持商品价格

    Serial,GoodCode,EvaluationDate,Price

  3. 价格有效,直到添加具有相同代码但日期不同的新行,从而更新其值

    现在,我想创建一个表格,根据购买日期将价格加到表格1中。 如果我们有:

      PurchaseDate  PurchasedGood
     -----------------------------
      05/20/2011      A111
    

      GoodCode  EvaluationDate  Price
     --------------------------------
       A111      02/01/2011     100
    ...
       A111      04/01/2011     110
    ...
       A111      06/01/2011     120
    

    结果将是

      PurchaseDate  PurchasedGood  Price
     -----------------------------------
      05/20/2011      A111          110
    

    首选方法是将视图Price1创建为

     Serial  GoodCode   StartDate  EndDate  Price
    

    然后通过

    加入这个观点的因素
      PurchasedDate between StartDate AND EndDate
    

    有人可以告诉我如何创建view1(或使用任何其他方法获取最终结果)?提前谢谢!

    P.S。抱歉我的英语不好!

1 个答案:

答案 0 :(得分:0)

  

我想创建一个表格,根据购买日期将价格加到表格中。

这是一个返回此类数据的查询。我相信语法是非常标准的SQL,但是这在SQL Server上进行了测试(看起来你可能正在使用带有“串行”命名的PostgreSQL)。

select a.FactorSerial, a.PurchasedGood, a.PurchaseDate
    , (select max(Price) from Prices where GoodCode = a.PurchasedGood and EvaluationDate = a.EvaluationDate) as Price
from (
    select f.FactorSerial, f.PurchasedGood, f.PurchaseDate, max(p.EvaluationDate) as EvaluationDate
    from Factors as f
        join Prices as p on f.PurchasedGood = p.GoodCode
    where f.PurchaseDate >= p.EvaluationDate
    group by f.FactorSerial, f.PurchasedGood, f.PurchaseDate
) as a

此查询假定在价格存在之前没有购买。

另外,考虑:

  

首选方法是将视图Price1创建为

Serial  GoodCode   StartDate  EndDate  Price
     

然后通过

加入这个观点的因素
 PurchasedDate between StartDate AND EndDate

between具有包容性。使用您所描述的此方法,如果PurchaseDate位于一行的EndDate和另一行的StartDate,则会出现重复。