日期:2014-05-17  浏览次数:20542 次

如何写多表联合查询语句
表A 表B 表C 表D
物料代码 图号 批次 物料代码 数量 批次 物料代码 数量 批次 物料代码 数量
a1 1001 X101 a1 10 Y101 b1 5 Z101 c1 54
b1 1001 X102 a2 4 Y102 b2 4 Z102 c2 1
c1 1001 X103 a1 6 Y103 b2 8 Z103 c2 96
a2 1002 X104 a1 1 Y104 b1 3 Z104 c2 7
b2 1002
c2 1002

结果
图号 表B物料 表B数量 表C物料 表C数量 表D物料 表D数量
1001 a1 b1 c1
1002 a2 b2 c2


------解决方案--------------------
引用:
Quote: 引用:

修改了一下查询语句:


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
inner 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数量
1001 a1     17     b1     8     c1     54
1002 a2     4     b2     12     c2     104
*/


可以直接用Select子查询吗,因为物料里面有些业务是空的


改成这样,你再试试:

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&nb