问题描述
要在以下条件下创建新表
- 如果table1.sid = table2.sid
然后是t1.totalcorrect + t2.totalcorrect,t1.totalquestions + t2.totalquestions。是s4到s7
- 两个表中的其他数据均是
预期输出
使用联接结果表只给我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 all
和group 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}}值合并为一行。