简体   繁体   English

将数据从另一表的一列插入到同一表的多列中

[英]Inserting data into multiple columns of same table from one column of another table

I have a table WCR (l,j,W,C,R) with the following entries.我有一个包含以下条目的表WCR (l,j,W,C,R) Here, l,j are primary keys.这里, l,j是主键。

在此处输入图片说明

I have to insert data from column C of WCR into another table C(l,C1,C2) where l is the primary key.我必须将数据从WCR C列插入到另一个表C(l,C1,C2) ,其中l是主键。 The C table will be as follows - C表如下-

在此处输入图片说明

For each l , j=1 will be inserted in C1 , and j=2 will be inserted into C2 .对于每个lj=1将插入C1j=2将插入C2 But I can not generalize the queries.但我无法概括这些查询。

I have tried statements like -我试过这样的陈述 -

INSERT INTO C 
SELECT 1, 
C FROM WCR WHERE j=1, 
C FROM WCR WHERE j=2;

and subqueries in Insert statement like -和 Insert 语句中的子查询,如 -

 INSERT INTO C 
 VALUES (1, 
         SELECT C FROM WCR WHERE j=1, 
         SELECT C FROM WCR WHERE j=2);

But none of them works in Vertica as it doesn't support subquery in INSERT statement and the first one is invalid.但是它们都不适用于 Vertica,因为它不支持INSERT语句中的子查询,并且第一个无效。 How can I efficiently Insert the values into C ?如何有效地将值插入C

One method uses a join :一种方法使用join

Insert into C(l, c1, c2)
    select wcr1.l, wcr1.c, wcr2.c
    from wcr wcr1 join
         wcr wcr2
         on wcr1.l = wcr2.l and wcr1.j = 1 and wcr2.j = 2;

Another method uses conditional aggregation:另一种方法使用条件聚合:

insert into c(l, c1, c2)
     select l, max(case when j = 1 then c end) as c1, max(case when j = 2 then c end)
     from wcr
     group by l;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM