【问题标题】:Oracle SQL: Update a table with difference in value from two other tablesOracle SQL:更新与其他两个表的值不同的表
【发布时间】:2022-01-18 19:48:27
【问题描述】:

我正在尝试为我的项目创建一种库存管理系统,并且非常感谢任何人提供的任何意见。 我正在尝试用我的CountUsed 表的值差异来更新一个表(Current)。

这是我的表格的简化版。

Count

date donor type_id count
03-JAN-20 Bob Rice 20
05-JAN-20 Jan Pasta 12
08-JAN-20 Bob Rice 8

Used

date type_id used
03-JAN-20 Rice 13
05-JAN-20 Pasta 5

我想用这个公式更新我的当前表。

select (a.ct - b.us) as diff
from
(select sum(count) as ct, type_id from NATHANIA.inventory_fact where type_id = 'Rice' group by type_id) a
left join
(
select sum(used) as us, type_id from NATHANIA.inventory_used where type_id = 'Rice' group by type_id) b
on a.type_id = b.type_id;

输出给我 15 (20+8-13)。我无法相应地更新我的 Current 表。

Current

type_id current_count
Rice 15
Pasta 2

我尝试使用 cte,但它给了我这个错误:“UPDATE ... SET 表达式必须是子查询”。

update NATHANIA.inventory_current t1
    set (t1.type, t1.current_count) = (
        with cte1 as ( 
            select a.ct-b.us as diff
            from
            (select sum(count) as ct, type_id from NATHANIA.inventory_fact where type_id = 'Rice' group by type_id) a
            left join
            (select sum(used) as us, type_id from NATHANIA.inventory_used where type_id = 'Rice' group by type_id) b
            on a.type_id = b.type_id
        )
    select type_id, diff from cte1 where t1.type = cte1.type_id
    );

如果我遗漏任何信息,请告诉我,这是我的第一个堆栈问题 :)

【问题讨论】:

    标签: sql oracle sql-update oracle-sqldeveloper


    【解决方案1】:

    我喜欢在这样的情况下使用 MERGE 语句 - 您的查询结果包含一个关键字段以及任何需要的新数据。 MERGE 是一种非常直接的方式来包装该查询并根据需要插入/更新/删除。

    https://docs.oracle.com/database/121/SQLRF/statements_9017.htm#SQLRF01606

    示例代码可能如下所示 - 尚未测试,但上面的链接提供了所有必要的语法详细信息:

    MERGE INTO NATHANIA.inventory_current t1
        USING (
            select a.type_id,
            (a.ct - b.us) as diff
            from
            (select sum(count) as ct, type_id from NATHANIA.inventory_fact where type_id = 'Rice' group by type_id) a
            left join
            (
            select sum(used) as us, type_id from NATHANIA.inventory_used where type_id = 'Rice' group by type_id) b
            on a.type_id = b.type_id
        ) s
    ON ( t1.type = s.type_id)
    WHEN MATCHED THEN UPDATE
    set t1.current_count = s.diff
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 2011-04-19
      • 2014-05-09
      相关资源
      最近更新 更多