これら2つの選択があります。違いは、結合テーブルと合計内のケースにあります
select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1
from table1
join table2 on table1.col3 = table2.col3
group by table1.col1
select
table1.col1
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table3 on table1.col3 = table3.col3
group by table1.col1
これらのクエリを単一の選択にマージするにはどうすればよいですか? 問題は、'C2' と同じように、'C1' のすべての行が table2 と結合されている場合にのみ必要です。これは結合の例です。両方の結合の col3 は (列のタイプに関して) 同等ですが、値は同等ではないことがわかります。
select table1.col1, table1.col2, table2.col3 from table1 join table2 on table1.col3 = table2.col3
table1.col1 | table1.col2 | table2.col3
'COD1' 'C1' 543
'COD1' 'C2' 329
'COD2' 'C2' 123
'COD1' 'C1' 943
select table1.col1, table1.col2, table3.col3 from table1 join table3 on table1.col3 = table3.col3
table1.col1 | table1.col2 | table3.col3
'COD2' 'C2' 632
'COD1' 'C1' 895
'COD1' 'C2' 248
'COD2' 'C1' 458