如何通过添加 Oracle 中另一个表中的值来更新特定表字段的值



我有两个表:

表1(来源表(:此表跟踪正在导入的所有数据

date     | type   | volume | words | words_per | none | none_per
07-APR-21    cats    , 10     , 5     ,  50        , 5    ,50
07-APR-21    dogs     , 10     , 5     ,  50        , 5    ,50
07-APR-21    primates , 10     , 5     ,  50        , 5    ,50
07-APR-21    seafish  , 10     , 5     ,  50        , 5    ,50
06-APR-21    cats    , 10     , 5     ,  50        , 5    ,50
06-APR-21    dogs     , 10     , 5     ,  50        , 5    ,50
06-APR-21    primates , 10     , 5     ,  50        , 5    ,50
06-APR-21    seafish  , 10     , 5     ,  50        , 5    ,50

表2(TARGET TABLE(:此表是汇总每个月值的主表

| type   | volume | words | words_per | none | none_per
cats      , 20     , 10    ,  50%        , 10    ,50%
dogs      , 20     , 10    ,  50%        , 10    ,50%
primates    , 20     , 10    ,  50%        , 10    ,50%
seafish    , 20     , 10    ,  50%        , 10    ,50%

该表是目标表,我希望通过从源表的数据中执行加法运算,不断按其各自的类型更新每个值。例如,volume字段是每种类型(10+10(的(07/4月+06/April(数据。单词也是一样,没有。每个/noe_per的单词只是单词/卷和none/volume。

这是我迄今为止的代码:

UPDATE table2
SET volume = table1.volume + table2.volume ,
words = table1.volume + table2.words,
words_per =  (table2.words / table2.volume ) * 100 ,
none =  table1.volume + table2.none ,
none_per = (table2.none / table2.volume ) * 100
WHERE type = 'cats', 'dogs', 'primates','seafish' and 
table1.date = SELECT TO_DATE(current_date - 1) 
AS yesterday_date 
FROM dual;

此处需要注意的事项

  1. 我只想从表1中收集最新的记录,这将是昨天的日期
  2. 我有两个计算字段-";none_per";以及";words_per";。该逻辑需要自动更新到其当前逻辑

我知道上面的代码可能很粗糙,但我是Oracle SQL的新手,所以任何关于如何修复或改进代码的想法或建议都会有所帮助。

您想要的不是平滑的更新,而是随着日期的推移进行合并,似乎不需要限制为前一天的日期,而是当前日期。尽管如此,我认为不需要对您的情况应用任何DML语句,一个带有聚合的简单视图就足以取代table2(即v_table1(,如

CREATE OR REPLACE VIEW v_table1 AS
SELECT type, 
SUM(NVL(volume,0)) AS volume, 
SUM(NVL(words,0)) AS words, 
AVG(NVL(words_per,0))||'%' AS words_per, 
SUM(NVL(none,0)) AS none, 
AVG(NVL(none_per,0))||'%' AS none_per
FROM table1
GROUP BY type 

最新更新