首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么写多表联合查询语句

2013-12-19 
如何写多表联合查询语句表A表B表C表D物料代码图号批次物料代码数量批次物料代码数量批次物料代码数量a1100

如何写多表联合查询语句
表A表B表C表D
物料代码图号批次物料代码数量批次物料代码数量批次物料代码数量
a11001X101a110Y101b15Z101c154
b11001X102a24Y102b24Z102c21
c11001X103a16Y103b28Z103c296
a21002X104a11Y104b13Z104c27
b21002
c21002

结果
图号表B物料表B数量表C物料表C数量表D物料表D数量
1001a1b1c1
1002a2b2c2

怎么写多表联合查询语句
[解决办法]

引用:
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数量
1001a1    17    b1    8    c1    54
1002a2    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 表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
*/

热点排行