在 Snowfalke 中添加计算列

问题描述

同样,我似乎找不到一种简单的方法来做到这一点。 但我已经编码了一段时间,可能我只是累了,失去了它!

SELECT 
case when "colA" = '1' OR "colB" = 1 then 1
    else 0
end as "colc"
FROM t1

如何将这个新列添加到 t1,保留顺序等?

我知道我能跑

ALTER t1 ADD COLUMN colc

但是如何正确填充值?

解决方法

尽管您可以找到相关文档,但实际上可以创建计算列。下面是一个例子:

create or replace table computedColTest (id bigint,id2 bigint,derived bigint as (id * id2));
insert into computedColTest values (3,5);
select * from computedColTest;

结果是:

enter image description here

但是,我认为无法直接翻译您需要的逻辑,因为您似乎无法在其中使用逻辑运算符。但是,您可以根据自己的情况稍微调整一下,并将您的开关转换为兼容的数学运算。

,

我认为“虚拟列”是 Snowflake 中派生列的已知方式。 看看这个:

CREATE 
OR REPLACE TABLE Virtual_Column_Example (
    colA INT,colB INT,derived INT AS ( IFF(colA = 1 or colB = 1,1,0) )
);

INSERT INTO Virtual_Column_Example 
    VALUES (0,0),(1,1),2),(2,2);

SELECT * FROM Virtual_Column_Example;

/*
---------------------
colA | colB | derived
---------------------
   0 |    0 |      0
   1 |    1 |      1
   1 |    2 |      1
   2 |    1 |      1
   2 |    2 |      0
---------------------
*/
,

我实际上找到了一种很好的方法,只需使用 UPDATE

ALTER TABLE t1 ADD COLUMN "col3" INTEGER DEFAULT 0;

UPDATE t1
SET "col3"= 1
WHERE "col1" = 1 OR "col2" = 1;