2014-01-22 48 views
0

如何使用這2個sql語句執行此操作?如何加入2 sql命令

select trade_date, count(*) from tableone group by trade_date order by trade_date; 
select trade_date, count(*) from tabletwo group by trade_date order by trade_date; 

我想加入這兩個語句來創建一個結果類似如下:

trade_date, tableone.count, tabletwo.count 

通過trade_date分組。

有人可以幫忙嗎?

回答

0

簡單連接

SELECT coalesce(a.trade_date,b.trade_date) as trdate, a.cnt , b.cnt FROM 
(SELECT trade_date, count(*) AS cnt FROM tableone GROUP BY trade_date) A 
LEFT OUTER JOIN 
(SELECT trade_date, count(*) AS cnt FROM tabletwo GROUP BY trade_date) B 
ON a.trade_date = b.trade_date 
ORDER BY trdate; 
+0

謝謝這個偉大的工作。現在我必須加入34條選擇語句。 urgh !!!! ... – froztwind

0

和你的敘述所面臨的挑戰是,當兩個表中交易日的列表是不一樣的。在這種情況下,你會希望有一個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); 
+0

sql失敗給我一個錯誤:ORA-00904:「T2」。「TRADE_DATE」:無效的標識符。我知道tabletwo有trade_date列,所以tableone也是如此。 – froztwind

+0

@ user3221575。 。我不知道爲什麼我把表的別名從'agg1'和'agg2'切換到't1'和't2'。但代碼是固定的。 –

+0

這個工作也很好。如果我不得不添加第三個表「tablethree」,這將如何看起來像?非常感謝。 – froztwind