I have a sql query like this,
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
and the result is like this;
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
but I want to show result like this;
ID A B C D
---- ------ ----- ----- ------
1773 100 120 200 60
how can I rewrite the query? thx for your help..
Just use
sum()andgroup by idto flatten it out:Efficient. Simple. Incidentally,
max()ormin()would work equally well.This works because your data only has one occasion for each field where there’s a non-null value; any aggregating function can pick that one value out from the nulls.