合并两个具有不同连接的选择句子

时间:2013-09-16 15:08:29

标签: sql oracle join

我有这两个选择,差异在连接表和总和

中的情况
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

如何将这些查询合并为一个选择?问题是我只想在与table2连接时使用所有'C1'行,与'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

3 个答案:

答案 0 :(得分:2)

如果你想要单列中的所有C1和C2,那么你可以去UNION或UNION ALL(还包括重复项):

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
union
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

如果你想在单独的列中使用C1和C2,那么你可以在第一个查询中简单地为C2列添加case语句:

select
table1.col1
sum(case when table1.col2 = 'C1' then table1.value else 0 end) as C1,
sum(case when table1.col2 = 'C2' then table1.value else 0 end) as C2
from table1
join table2 on table1.col3 = table2.col3
join table3 on table1.col3 = table3.col3

答案 1 :(得分:0)

我不确定我是否真的理解这个问题,但

select col1, C1, C2
from table
left join ( ... first query ...) as t1 using(col1)
left join ( ... second query ...) as t2 using(col2)

使用这种技术,您可以将子查询转换为连接。

答案 2 :(得分:0)

假设您的查询应该有明显的group by子句,您可以执行以下操作:

select t1.col1,
       sum(case when t1.col3 in (select col3 from table2) and
                     t1.col2 = 'C1'
                then t1.value else 0
           end) as C1,
       sum(case when t1.col3 in (select col3 from table3) and
                     t1.col2 = 'C2'
                then t1.value else 0
           end) as C2
from table1 t1
group by t1.col1;

我会提醒你做明确的连接。 <{1}}和table2中的多个匹配行会甩掉您的总和。