Справка по db2 sql left join table - PullRequest
1 голос
/ 07 июля 2011

У меня есть 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

как мне переписать запрос?спасибо за вашу помощь ..

Ответы [ 2 ]

4 голосов
/ 07 июля 2011

Просто используйте 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() будет работать одинаково хорошо.

Это работает, потому что ваши данные имеют только один случай для каждого поля, где есть ненулевое значение; любая агрегирующая функция может выбрать одно значение из нуля.

2 голосов
/ 07 июля 2011

как насчет вложенных запросов для каждого значения?

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

Это далеко не оптимально, но работает

...