2013-09-16 25 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中的多個匹配行會甩掉你的錢。