2011-07-07 57 views
1

我有一個SQL查詢這個樣子,DB2 SQL左連接表的幫助

select 
    t1.id as ID, 
    case when t2.field1 = 1102 then (t2.field3 - t2.field2) end as A, 
    case when t2.field1 = 1112 then (t2.field3 - t2.field2) end as B, 
    case when t2.field1 = 1113 then (t2.field3 - t2.field2) end as C, 
    case when t2.field1 = 1106 then (t2.field3 - t2.field2) end as D 
    from table1 t1 
    left join table2 t2 
    on t1.id = t2.id 

,結果是這樣的;

ID A  B  C  D 
---- ------ ----- ----- ------ 
1773 100 NULL NULL NULL 
1773 NULL 120 NULL NULL 
1773 NULL NULL 200 NULL 
1773 NULL NULL NULL 60 

但我想顯示這樣的結果;

 ID A  B  C  D 
    ---- ------ ----- ----- ------ 
    1773 100 120 200 60 

我該如何重寫查詢? thx爲您的幫助..

+0

是否所有的行都有相同的ID? –

+0

是的,所有行都有相同的ID – vtokmak

回答

4

只需使用sum()group by id來壓平:

select 
t1.id as ID, 
sum(case when t2.field1 = 1102 then (t2.field3 - t2.field2) end) as A, 
sum(case when t2.field1 = 1112 then (t2.field3 - t2.field2) end) as B, 
sum(case when t2.field1 = 1113 then (t2.field3 - t2.field2) end) as C, 
sum(case when t2.field1 = 1106 then (t2.field3 - t2.field2) end) as D 
from table1 t1 
left join table2 t2 on t1.id = t2.id 
group by 1; 

高效。簡單。順便提一下,max()min()可以很好地工作。

這是可行的,因爲您的數據只有一個每個字段有一個非空值的場合;任何聚合函數都可以從空值中選出一個值。

+0

+1。我同意你的意見 – niktrs

+0

thx爲你的幫助,它的工作;) – vtokmak

2

如何嵌套查詢每個值?

select t1.id as ID,  
    (select t2.field3 - t2.field2 from table2 t2 
    where t1.id = t2.id and t2.field1 = 1102) as A,  
    (select t2.field3 - t2.field2 from table2 t2 
    where t1.id = t2.id and t2.field1 = 1112) as B,  
    (select t2.field3 - t2.field2 from table2 t2 
    where t1.id = t2.id and t2.field1 = 1113) as C,  
    (select t2.field3 - t2.field2 from table2 t2 
    where t1.id = t2.id and t2.field1 = 1106) as D,  
from table1 t1 

這是遠遠沒有達到最佳,但它的工作原理

+0

thx爲您提供幫助,您的代碼也可以正常工作;) – vtokmak