我们可以在大查询 table 上使用带有 INSERT 的 CASE 语句吗?

Can we use CASE statement with INSERT on a big query table?

我正在尝试在没有连接的情况下从另一个子 table 中附加与主 table 中的唯一键值相对应的值。

例如:

MAIN_TABLE:

COL1 | COL2 | COL3
aaa  | 1111 | a111 
bbb  | 2222 | b222 
ccc  | 3333 | c333 
ddd  | 4444 | d444 
abc  | 1233 | b222 

SUB_TABLE

COL1 | COL2
Cat  | a111
Dog  | b222
bird | c333
fish | d444

我需要如下的结果

COL1 | COL2 | COL3 | COL4
aaa  | 1111 | a111 | Cat 
bbb  | 2222 | b222 | Dog 
ccc  | 3333 | c333 | Bird
ddd  | 4444 | d444 | fish
abc  | 1233 | b222 | Dog

我试图通过在 BigQuery 的 Col 4 中使用 CASE 语句来实现这一点。

我很想知道是否有任何其他方法可以在没有连接的情况下解决这个问题,而是将值作为新列映射到 table。

提前感谢您的宝贵时间。 请帮忙!

如果col2sub_table中是唯一的,可以使用子查询:

select m.*,
    (select s.col1 from sub_table s where s.col2 = m.col3) as col4
from main_table m

或者您可以加入:

select m.*, s.col1
from main_table m
inner join sub_table s on s.col2 = m.col3

不清楚您在问题中 insert 的意思。如果你想在 main_table 的现有行中更新 col4,你可以这样做:

update main_table m
set col4 = (select s.col1 from sub_table s where s.col2 = m.col3)

以下适用于 BigQuery 标准 SQL

#standardSQL
select m.*, s.col1 as col4 
from main_table m
left join sub_table s
on s.col2 = m.col3    

如果应用于您问题中的示例数据 - 输出为

试试这个查询:

select m.*, s.col1 as col4 from sub_table s,main_table m where s.col2 = m.col3