2013-09-16 23 views
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 

如何合并这些querys成一个单一的选择内部的情况?问题是我只希望所有'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 
+0

。 。您的查询在语法上不正确。他们在'select'中有'sum()'函数,但不是'group by'。 –

+0

@GordonLinoff你是对的,编辑 –

回答

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在单独的列,那么你可以在你的第一个查询简单的附加case语句列C2:

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 
+0

对于你的第二个查询,我希望'C2'行独占于table3 –

+0

然后你可以在查询中添加一个连接。我编辑了第二个查询供您参考。 – Sonam

0

我不知道我真正理解这个问题,但怎么样

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

使用这种技术,你可能可以将子查询为连接。

+0

我不确定我明白...每次加入后'开'在哪里? –

+0

我正在使用“使用”而不是(几乎)等价于(left.col1 == rigt.col2)。我犯了一个错字是应该使用(col1) – mb14

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; 

我要提醒你做明确连接。 table2table3中的多个匹配行会甩掉你的钱。