【问题标题】:Is there any way to add the result column of SELECT to an already existing table in mySQL8?有什么方法可以将 SELECT 的结果列添加到 mySQL8 中已经存在的表中?
【发布时间】:2020-09-02 19:20:38
【问题描述】:

我正在尝试使用我是 mySQL 的窗口函数来查找股票价格的 SMA。我可以使用 SELECT 语句完成此操作,但是 ALTER 表语句不允许我使用窗口函数。我的想法是使用 select 语句来查找平均值并将原始表与其返回的列连接起来:

SELECT 
date_, close, AVG(close) OVER (ORDER BY date_ ASC ROWS 11 PRECEDING) AS SMA12 FROM intel_stock;

从原始表返回一个包含 3 行的表

有没有办法将新计算的行“添加/插入/加入/联合”到原始表的右侧(假设我已经添加了一个额外的空列)?

【问题讨论】:

标签: mysql sql database sql-update window-functions


【解决方案1】:

您需要先添加该列,然后再对其进行更新。 update ... join 语法对于第二步很方便。

-- add the new column
alter table intel_stock add column sma12 float; -- or whathever datatype is needed

-- set the new column
update intel_stock ist
inner join (
    select 
        date_, 
        avg(close) over (order by date_ rows 11 preceding) as sma12
    from intel_stock
) ist1 on ist1.date_ = ist.date_
set ist.sma12 = ist1.sma12

请注意,使用视图存储派生信息可能更简单。这样就省去了在周围行中的数据发生变化时维护新列的繁琐任务:

create view intel_stock as
select 
    is.*, 
    avg(close) over (order by date_ rows 11 preceding) as sma12
from intel_stock

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多