DB2SQL左联接表帮助
我有这样一个sql查询DB2SQL左联接表帮助,sql,db2,left-join,Sql,Db2,Left Join,我有这样一个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,
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
但我想展示这样的结果
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
如何重写查询?谢谢您的帮助。每个值的嵌套查询如何
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
这远不是最优的,但它可以工作对每个值进行嵌套查询怎么样
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()
和按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()
也同样适用
这是因为您的数据对于每个字段只有一次非空值;任何聚合函数都可以从空值中选择一个值。只需使用sum()
和按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()
也同样适用
这是因为您的数据对于每个字段只有一次非空值;任何聚合函数都可以从空值中选择一个值。所有行是否具有相同的ID?所有行是否具有相同的ID?