使用表中的值更新新SQL列

djq*_*djq 1 sql insert

我正在使用SQL执行基本计算,我无法弄清楚正确的语法.我有一个表,我想添加一个新列,并使用现有值的组合填充该列的值.这是我用来解释问题的代码.

-- create a table
CREATE TABLE test (
x numeric(10,3),
y numeric(10,3)
);

-- add some sample values
INSERT INTO test (x,y) VALUES( 7,3 );
INSERT INTO test (x,y) VALUES( 8,4 );

-- add a new column
ALTER TABLE test ADD testcalc numeric(10,3);

-- values in new column (testcalc) using the sum of values from x and y
INSERT INTO 
    test (testcalc) 
SELECT 
    t.x + t.y
FROM
    test as t;
Run Code Online (Sandbox Code Playgroud)

这会产生下表:

在此输入图像描述

我理解这些值是作为新行插入的,但是如何将它们作为值添加到我的列中,以便表格的结构如下?

x | y | testcalc
7 | 3 | 10
8 | 4 | 12
Run Code Online (Sandbox Code Playgroud)

Ole*_*Dok 8

您需要在查询的最后部分使用UPDATE而不是INSERT这样的方式:

UPDATE test SET
testcalc = x + y

SELECT * FROM test
Run Code Online (Sandbox Code Playgroud)