如何将选择结果存储到同一表的新列中?

时间:2019-04-18 12:34:08

标签: sql db2

我正在使用IBM的DB2。我有桌子 stockdb(date, close) 我正在计算它的30天移动平均线,并将其存储在同一张表中。

alter stockdb 
add ma as avg("close") 
over
(order by "date" rows between 29 preceding and current row)
from stockdb;

3 个答案:

答案 0 :(得分:1)

您不能作为计算列来执行此操作,因为不允许使用窗口函数。改用视图:

create view v_stockdb as 
    select s.*,
           avg("close") over (order by "date" rows between 29 preceding and current row) as ma
    from stockdb s;

答案 1 :(得分:0)

INSERT INTO stockdb 
( date, 
  close, 
  ma
) 
VALUES 
( 
  CURRENT DATE,
  1.00,
  (select avg("close") 
          over (order by "date" rows between 29 preceding and current row ) 
    from stockdb )
)

值是任意的,我可以/应该同样容易地使用bind parms(?)。我注意到您的表没有符号,打开,高或低,因此如果您更改表,则必须添加这些符号。

答案 2 :(得分:0)

没有示例数据;我假设您每个日期有1行,而收盘价可能是收盘零售价或商店的价格?

您能做到这一点吗?

  1. 将平均列添加到您的表中-我将其设置为9.2小数点;
    ALTER TABLE STOCKDB                      
    ADD COLUMN MA DEC (9 , 2) NOT NULL WITH DEFAULT;
  1. 更新表格,将平均值添加到该列;
UPDATE STOCKDB B                                        
   SET MA = (SELECT XMA                                         
               FROM (                                           
                SELECT "DATE",AVG("CLOSE")                      
                       OVER (ORDER BY "DATE" ROWS               
                       BETWEEN 29 PRECEDING AND CURRENT ROW) XMA
                FROM RAKELLR/STOCKDB) Z                         
              WHERE Z."DATE" = B."DATE")         

因此,您可以在表“ Z”中建立日期和平均值-调用平均值行XMA;

    SELECT "DATE",AVG("CLOSE")                      
           OVER (ORDER BY "DATE" ROWS               
           BETWEEN 29 PRECEDING AND CURRENT ROW) XMA
    FROM STOCKDB) Z; 

然后更新STOCKDB表,将MA列设置为日期匹配的= XMA;

UPDATE STOCKDB B                                        
   SET MA = (SELECT XMA                                         
               FROM (...Z...)                         
              WHERE Z."DATE" = B."DATE");