和你的敘述所面臨的挑戰是,當兩個表中交易日的列表是不一樣的。在這種情況下,你會希望有一個full outer join
:
select coalesce(agg1.trade_date, agg2.trade_date) as trade_date,
coalesce(cnt1, 0) as cnt1,
coalesce(cnt2, 0) as cnt2
from (select trade_date, count(*) as cnt1
from tableone
group by trade_date
) agg1 full outer join
(select trade_date, count(*) as cnt2
from tabletwo
group by trade_date
) agg2
on agg1.trade_date = agg2.trade_date
order by coalesce(agg1.trade_date, agg2.trade_date);
編輯:
三個用表,代碼的結構非常相似:
select coalesce(agg1.trade_date, agg2.trade_date, agg3.trade_date) as trade_date,
coalesce(cnt1, 0) as cnt1,
coalesce(cnt2, 0) as cnt2,
coalesce(cnt3, 0) as cnt3
from (select trade_date, count(*) as cnt1
from tableone
group by trade_date
) agg1 full outer join
(select trade_date, count(*) as cnt2
from tabletwo
group by trade_date
) agg2
on agg1.trade_date = agg2.trade_date full outer join
(select trade_date, count(*) as cnt3
from tablethree
group by trade_date
) agg3
on agg3.trade_date = coalesce(agg1.trade_date, agg2.trade_date)
order by coalesce(agg1.trade_date, agg2.trade_date, agg3.trade_date);
謝謝這個偉大的工作。現在我必須加入34條選擇語句。 urgh !!!! ... – froztwind