db2 sql left join table help -
db2 sql left join table help -
i have sql query this,
select t1.id id, case when t2.field1 = 1102 (t2.field3 - t2.field2) end a, case when t2.field1 = 1112 (t2.field3 - t2.field2) end b, case when t2.field1 = 1113 (t2.field3 - t2.field2) end c, case when t2.field1 = 1106 (t2.field3 - t2.field2) end d table1 t1 left bring together table2 t2 on t1.id = t2.id and result this;
id b c d ---- ------ ----- ----- ------ 1773 100 null null null 1773 null 120 null null 1773 null null 200 null 1773 null null null 60 but want show result this;
id b c d ---- ------ ----- ----- ------ 1773 100 120 200 60 how can rewrite query? thx help..
just utilize sum() , group id flatten out:
select t1.id id, sum(case when t2.field1 = 1102 (t2.field3 - t2.field2) end) a, sum(case when t2.field1 = 1112 (t2.field3 - t2.field2) end) b, sum(case when t2.field1 = 1113 (t2.field3 - t2.field2) end) c, sum(case when t2.field1 = 1106 (t2.field3 - t2.field2) end) d table1 t1 left bring together table2 t2 on t1.id = t2.id grouping 1; efficient. simple. incidentally, max() or min() work as well.
this works because info has one occasion each field there's non-null value; aggregating function can pick 1 value out nulls.
sql db2 left-join
Comments
Post a Comment