2016-07-08 3 views
0

に異なるテーブルの三の以上の同一の列からのデータをマージ: 表1次のように私は月、アイテムと三つの異なるテーブルを有する単一の列

month books 
April-2016 2 
February-2016 7 
January-2016 1 
June-2016 6 
May-2016 1 
September-2015 1 

表2

month copies 
April-2016 92 
August-2015 1 
February-2016 49 
January-2016 5 
June-2016 127 

表3

month pens 
February-2016 74 
January-2016 1 
June-2016 66 
March-2016 136 
May-2016 128 

今、私はこのようなものを探していました: mon第書籍コピーこのようなIは

select COALESCE(t1.Month,t2.Month,t3.Month) AS [Month], 
ISNULL(t1.books,0) AS books, 
ISNULL(tp.copies,0) AS copies, 
ISNULL(tn.pens,0) AS pens 
from #table1 t1 
full join #table t2 on t1.month=t2.month 
full join #table t3 on t1.month=t3.month 
と試み

month books copies pens 
April-2016 2 92 0 
September-2015 1 0 0 
August-2015 0 1 0 
June-2016 6 127 66 

ように(データが利用可能でない場合、0が配置されるべきである) -the月列がマージされるべきであり、他のデータは、それぞれの列に配置する必要がありペン

---連合は私に6列を与えてくれるので動作しません。(1つしか必要ないところでは3ヶ月)

+3

あなたのクエリに何が問題なのですか? –

+2

クエリが同じテーブルから3回データを取得しています。私はそれがあなたがすることを意味しているとは思わない。正直言って、あなたのデザインに欠陥があるので、データを取得するのに問題があるという理由があります。アイテムの種類ごとにテーブルを用意するべきではありません。項目のタイプを示す列が必要です。 –

+0

@Sean Lange - 私は、新しいテーブルに結果を挿入することを望んでいました... – AjahnCharles

答えて

3

私がこれを行うには、月を作業表次に、各ソース表を順番に結合して、列1を選択します 一つ。各テーブルに同じ月のリストがあることがわかっている場合は、月の抽出は必要ありません。

select a.month, 
     t1.books, 
     t2.copies, 
     t3.pens 
    from (
select month from table1 
union 
select month from table2 
union 
select month from table3) a 
left join table1 t1 
    on a.month = t1.month 
left join table2 t2 
    on a.month = t2.month 
left join table3 t3 
    on a.month = t3.month 
2

full joinでこれを行うことができます。それは次のようになります。

select COALESCE(t1.Month,t2.Month,t3.Month) AS [Month], 
     COALESCE(t1.books,0) AS books, 
     COALESCE(t2.copies,0) AS copies, 
     COALESCE(t3.pens,0) AS pens 
from #table1 t1 full join 
     #table t2 
     on t2.month = t1.month full join 
     #table t3 
     on t3.month = coalesce(t1.month, t2.month); 

を個人的に、私はunion all/group by方法は、おそらく最も直感的です見つける:

select month, 
     sum(books) as books, sum(copies) as copies, sum(pens) as pens 
from ((select month, books, 0 as copies, 0 as pens from #table1 
    ) union all 
     (select month, 0 as books, copies, 0 as pens from #table2 
    ) union all 
     (select month, 0 as books, 0 as copies, pens from #table3 
    ) 
    ) bcp 
group by month; 

マイクによって提案left join方法も非常に合理的です。しばしば、私は2つの場所で各テーブルをリストする必要はありません。後でクエリを更新すると、エラーが発生する可能性があります。

+0

Mike Christie&Gordon Linoff:両方のアプローチがうまくいきました...しかし、クエリの最適化のための最適なオプションは何か教えてください(クエリ実行時間の点では...) – Aarush

+1

@ LearnByExample。 。 。パフォーマンスを得るには、妥当なサイズのデータ​​で両方のクエリをシステム上でテストする必要があります。どちらのバージョンでもより良いパフォーマンスが得られる状況があります。 –

関連する問題