2011-07-07 35 views
1

DB2のSQLは、テーブルのヘルプ私はこのような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

に動作します:

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()も同様に機能します。

これは、ヌル以外の値があるフィールドごとにデータがの1つで、の場合にのみ発生します。任意の集約関数は、その1つの値をヌルから取り出すことができます。

+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 

それははるかに最適なのだが、それはちょうどそれを平らにsum()group by idを使用

+0

あなたの助けにthx、あなたのコードも動作します;) – vtokmak

関連する問題