对令人困惑的问题标题道歉,但我不确定如何描述手头的问题。
我在Oracle 9i中有两个表:
Pricing
-------
SKU
ApplicableTime
CostPerUnit
Inventory
---------
SKU
LastUpdatedTime
NumberOfUnits
Pricing
包含在特定Unix时间对每个特定SKU项目的成本的增量更新。例如,如果我有记录:
SKU ApplicableTime CostPerUnit
------------------------------------
12345 1000 1.00
12345 1500 1.50
,然后项目12345在1000到1500之间的任何时间内每单位1.00美元,在1500之后的任何时间都是1.50美元。
Inventory
包含SKU,上次更新时间和单位数。
我尝试做的是构建一个查询,以便对Inventory
中的每一行,基于SKU加入两个表,我找到Pricing.ApplicableTime
的最大值。不大于Inventory.LastUpdatedTime
,从CostPerUnit
获取该特定记录的Pricing
,并计算TotalCost = CostPerUnit * NumberOfUnits
:
SKU TotalCost
-----------------------------------------------------------------------------------
12345 (CostPerUnit at most recent ApplicableTime <= LastUpdatedTime)*NumberOfUnits
12346 <same>
... ...
我该怎么做?
答案 0 :(得分:2)
SELECT *
FROM
(select p.SKU,
p.ApplicableTime,
p.CostPerUnit*i.NumberOfUnits as cost,
row_number over (partition by p.SKU order by p.ApplicableTime desc) as rnk
from Pricing p
join
Inventory i on (p.sku = i.sku and i.LastUpdatedTime > p.ApplicableTime)
)
where rnk=1
答案 1 :(得分:1)
select SKU, i1.NumberOfUnits * p1.CostPerUnit as TotalCost
from Inventory i1,
join (
select SKU, max(ApplicableTime) as ApplicableTime, max(i.LastUpdatedTime) as LastUpdatedTime
from Pricing p
join Inventory i on p.sku = i.sku
where p.ApplicableTime < i.LastUpdatedTime
group by SKU
) t on i1.sku = t.sku and i1.LastUpdatedTime = t.LastUpdatedTime
join Pricing p1 on p1.sku = t.sku and p1.ApplicableTime = t.ApplicableTime