SQL根据订单日期查找活动成本

时间:2018-05-25 16:45:28

标签: sql oracle

我的公司使用标准成本计算,我想知道在订购时找到与项目相关的成本的最佳方法吗?我使用SQL提取数据(不将数据放入表中)。

例如,我有项目ABC的这些费用:

 Update Date      Cost
 12/26/2017       $40
 2/1/2017         $43
 12/27/2016       $39

在另一张表中,我有项目ABC的这些订单:

Order Date        Price
1/1/2018          $80
1/1/2017          $84

以下是如何将数据整合在一起,但我不知道如何:

Order Date        Price     Cost
1/1/2018          $80       $40
1/1/2017          $84       $39

感谢您的建议!

2 个答案:

答案 0 :(得分:3)

您可以使用相关子查询执行此操作:

select o.*,
       (select c.cost
        from costs c
        where c.updatedate <= o.orderdate
        order by c.updatedate desc
        fetch first 1 row only
       ) as cost
from orders o;

这使用ANSI标准语法。数据库如何将结果限制为一行可能会有所不同。

编辑:

在早期版本的Oracle中,有多种方法可以解决这个问题。这是一种方法:

select o.*,
       (select max(c.cost) keep (dense_rank first order by c.updatedate desc)
        from costs c
        where c.updatedate <= o.orderdate
       ) as cost
from orders o;

答案 1 :(得分:0)

with costs (UpdateDate,Cost) as (
select to_date ('10/27/2017', 'mm/dd/yyyy'),60 from dual union all
select to_date ('11/25/2017', 'mm/dd/yyyy'),50 from dual union all
select to_date ('12/26/2017', 'mm/dd/yyyy'),40 from dual union all
select to_date ('2/1/2017',   'mm/dd/yyyy'),43 from dual union all
select to_date ('11/27/2016', 'mm/dd/yyyy'),39 from dual union all
select to_date ('12/27/2016', 'mm/dd/yyyy'),35 from dual 
)
, orders (OrderDate,Price) as (
select to_date('1/1/2018','mm/dd/yyyy'),80 from dual union all
select to_date('1/1/2017','mm/dd/yyyy'),84 from dual
)
select orderdate, price, 
       max(updatedate) updt, 
       max(cost) keep(dense_rank first order by updatedate desc) cost
from (
  select * from orders join costs on (orders.orderdate >= costs.updatedate)
)
group by orderdate, price;