2011-07-07 5 views
1

J'ai une requête SQL comme celui-ci,db2 sql gauche table de jointure aide

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 

et le résultat est comme celui-ci;

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 

mais je veux montrer le résultat comme ceci;

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

Comment puis-je réécrire la requête? merci pour votre aide ..

+0

Toutes les lignes ont-elles le même ID ou non? –

+0

Oui, toutes les lignes ont le même ID – vtokmak

Répondre

4

Il suffit d'utiliser sum() et group by id pour l'aplatir:

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; 

efficace. Simple. Incidemment, max() ou min() fonctionnerait tout aussi bien.

Cela fonctionne parce que vos données ont seulement un occasion pour chaque champ où il y a une valeur non nulle; toute fonction d'agrégation peut choisir cette valeur parmi les valeurs nulles.

+0

+1. Je suis d'accord avec vous – niktrs

+0

thx pour votre aide, ça marche;) – vtokmak

2

qu'en est-il des requêtes imbriquées pour chaque valeur?

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 

Il est loin d'être optimale, mais cela fonctionne

+0

thx pour votre aide, votre code fonctionne également;) – vtokmak