Oracle 历史报告 - 某个时间点的行是什么

Oracle historical reporting - what was the row at a point in time

我被要求 运行 一份固定时间点(2019 年 1 月 1 日)的资产状况报告。

这个数据库的编写方式是,资产有自己的 table 和当前信息,然后对于各种数据位,还有该信息更改的历史记录,每个位都存储自己的"history" table 带有开始和结束日期。因此,例如信息位之一是资产 class - 资产 table 将有一个包含当前资产 class 的字段,然后如果 class 已更改在过去,asset_history table 中会有包含开始日期和结束日期的行。像...

AssetID AssetClass StartDate EndDate
------- ---------- --------- -------
      1          1 12-12-87  23-04-90
      1          5 23-04-90  01-02-00
      1          2 01-02-00  27-01-19
      1          1 27-01-19

因此此资产已更改 classes 几次,但我需要编写一些内容以便能够检查每个资产,并计算出哪个 class 是活动的 class 截至 1 月 1 日。对于此示例,这将是倒数第二行,因为它在 2000 年更改为 class 2,然后在 2019 年 1 月 1 日之后变为 class 1.

为了让它变得更复杂,我将需要它来处理几位数据,但如果我能理解如何正确地做到这一点,那么我很乐意将其转换为其他数据。

如有指点,将不胜感激!

我通常这样写

select assetClass
from history_table h
 where :point_in_time >= startDate
   and (:point_in_time < endDate
        or endDate is null)

(假设这些列实际上是 date 类型而不是 varchar2

between 似乎总是很诱人,但它包括两个端点,因此您必须编写类似 :point_in_time between startDate and (endDate - interval '1' second)

的内容

编辑:如果您在第一次 start_date 之前尝试使用 point_in_time 运行 此查询,您将不会得到任何结果结果。这对我来说似乎很正常,但也许你想选择 "the first result which hasn't expired yet",像这样:

select assetClass
from history_table h
 where (:point_in_time < endDate
        or endDate is null)
order by startDate asc
fetch first 1 row only