Table 1
DATE dt
int amt
Table 2
DATE dt
int amt
每个表中的日期列不是唯一的。我希望能够看到任何一个表中存在的任何日期的每个金额的总和如下:
date t1.amt t2.amt
...
据我所知:
select coalesce(t1.dt, t2.dt), t1.amount, t2.amount from
(Select dt, sum(amt) from t1 group by dt) As t1
left join
(SELECT dt, sum(amt) from t2 group by dt) as t2
on (t1.dt = t2.dt);
然后,我尝试执行右连接(完成外连接)的所有内容只会给我语法错误。问题似乎与表别名有关。
如果有人可以帮我完成外部联接,我将不胜感激。 :)
感谢您阅读此内容。
答案 0 :(得分:0)
使用union all
和group by
:
select dt, sum(amt)
from ((select dt, amt from t1) union all
(select dt, amt from t2)
) tt
group by dt;
如果您希望它们位于不同的列中,请使用两列:
select dt, sum(amt1), sum(amt2)
from ((select dt, amt as amt1, NULL as amt2 from t1) union all
(select dt, NULL, amt from t2)
) tt
group by dt;