通过添加其他两个表的列在Redshift中创建表

问题描述

我想通过添加其他两个表的列在Redshift中创建一个表。

表1

Table 1 data


表2

Table 2 data

要在以下条件下创建新表

  1. 如果table1.sid = table2.sid
    然后是t1.totalcorrect + t2.totalcorrect,t1.totalquestions + t2.totalquestions。是s4到s7
  2. 两个表中的其他数据均是

预期输出

Output table

使用联接结果表只给我S4到S7,而不是其他所需的列。请帮助我

解决方法

那是full join

select 
    coalesce(t1.sid,t2.sid) sid,coalesce(t1.totalcorrect,0) + coalesce(t2.totalcorrect,0) totalcorrect,coalesce(t1.totalquestions,0) + coalesce(t2.totalquestions,0) totalquestions
from t1 
full join t2 on t2.sid = t1.sid
,

有两种方法可以做到这一点,我不确定在Redshift中哪种方法更快。一个是union allgroup by

select sid,sum(totalcorrect) as totalcorrect,sum(totalquestions) as totalquestions
from ((select sid,totalcorrect,totalquestions
       from t1
      ) union all
      (select sid,totalquestions
       from t2
      )
     ) t
group by sid;

第二个使用full join,我建议使用using子句:

select sid,0) as totalcorrect,0) as totalquestions
from t1 full join
     t2
     using (sid);

这两种方法之间存在差异。第一个保证结果集中的每个sid有一行,即使其中一个表中有重复项也是如此。第一种方法还将NULL的{​​{1}}值合并为一行。