我有这两个选择,不同之处在于连接表和总和内的情况
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
如何将这些查询合并到一个选择中?问题是我想要所有的'C1'行只有在与table2连接时,与'C2'相同。这是连接的一个示例,您可以看到两个连接中的 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