【问题标题】:Finding StartDate,EndDate from overriding StartDates从覆盖 StartDates 中查找 StartDate,EndDate
【发布时间】:2012-04-02 11:52:00
【问题描述】:

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

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

    FactorSerial, PurchaseDate, PurchasedGood

  2. “价格”表保存不同日期的商品价格

    序列号、GoodCode、评估日期、价格

在添加具有相同代码但不同日期的新行并因此更新其值之前,价格有效

现在,我想创建一个表格,根据购买日期将价格添加到表格 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

然后通过

将Factors与此视图结合起来
  PurchasedDate between StartDate AND EndDate

谁能告诉我如何创建 view1(或使用任何其他方法获得最终结果)?提前致谢!

附:对不起我的英语不好!

【问题讨论】:

  • 您使用的是哪个 RDBMS(SQLServer、Oracle、MySQL 等)?

标签: sql join date-range


【解决方案1】:

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

这是一个返回此类数据的查询。我相信语法是相当标准的 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

然后通过

将Factors与此视图结合起来
 PurchasedDate between StartDate AND EndDate

between 包含在内。使用您描述的这种方法,如果 PurchaseDate 位于一行的 EndDate 和另一行的 StartDate 上,您将得到重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多