如何写多表联合查询语句
表A表B表C表D
物料代码图号批次物料代码数量批次物料代码数量批次物料代码数量
a11001X101a110Y101b15Z101c154
b11001X102a24Y102b24Z102c21
c11001X103a16Y103b28Z103c296
a21002X104a11Y104b13Z104c27
b21002
c21002
结果
图号表B物料表B数量表C物料表C数量表D物料表D数量
1001a1b1c1
1002a2b2c2
[解决办法]
select a.图号,
MIN(case when flag = 'B' then t.物料代码 else null end) as 表B物料,
sum(case when flag = 'B' then t.数量 else 0 end) as 表B数量,
MIN(case when flag = 'C' then t.物料代码 else null end) as 表C物料,
sum(case when flag = 'C' then t.数量 else 0 end) as 表C数量,
MIN(case when flag = 'D' then t.物料代码 else null end) as 表D物料,
sum(case when flag = 'D' then t.数量 else 0 end) as 表D数量
from 表A a
left join
(
select 物料代码,数量,'B' flag from 表B union all
select 物料代码,数量,'C' from 表C union all
select 物料代码,数量,'D' from 表D
)t
on a.物料代码 = t.物料代码
group by a.图号
/*
图号 表B物料表B数量表C物料表C数量表D物料表D数量
1001a1 17 b1 8 c1 54
1002a2 4 b2 12 c2 104
*/