【问题标题】:SQL Find Active Cost Based on Order DateSQL 根据订单日期查找活动成本
【发布时间】:2018-05-30 10:32:20
【问题描述】:

我的公司使用标准成本核算,我想知道在订购商品时找到与商品相关的成本的最佳方法是什么?我正在使用 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

感谢您的建议!

【问题讨论】:

  • 在订单中添加成本列,在创建订单时在订单中插入成本。不要试图追溯计算。
  • 用您正在使用的数据库标记您的问题。

标签: sql oracle


【解决方案1】:

您可以使用相关子查询来做到这一点:

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;

【讨论】:

  • 感谢您的回复。非常有帮助。如所写,它在 Order By 语句之前引发缺少右括号错误。一些研究表明它不喜欢 order 语句,因为它是为选择一行而编写的。有什么想法吗?
  • @ERKSMTY 。 . .从 Oracle 12 开始,Oracle 支持 fetch first 1 row only
【解决方案2】:
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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 2017-03-23
    相关资源
    最近更新 更多