我被要求在固定的时间点(2019年1月1日)报告我们的资产状况。
这个数据库编写的方式是资产有自己的表和当前信息,然后对于各种数据位,也有信息变化的历史记录,每个位都存储着自己的“历史”表,其中包含一个开始和结束日期。因此,例如,其中一个信息是资产类 - 资产表将包含一个包含当前资产类的字段,然后如果该类在过去发生了变化,那么asset_history表中将有开始和结束的行日期。就像是...
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
所以这个资产已经改变了几次类,但我需要写一些东西,以便能够检查每个资产,并确定哪个类是活动类,如1月1日。对于这个例子,这将是第二个 - 从最后一个因为它在2000年改为2级,然后在2019年1月1日之后变成了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运行此查询,则不会得到任何结果。这对我来说似乎很正常,但也许您想要选择“尚未过期的第一个结果”,如下所示:
select assetClass
from history_table h
where (:point_in_time < endDate
or endDate is null)
order by startDate asc
fetch first 1 row only