34,576
社区成员
发帖
与我相关
我的任务
分享
if OBJECT_ID('[a]') is not null drop table [a]
if OBJECT_ID('[b]') is not null drop table [b]
if OBJECT_ID('[c]') is not null drop table [c]
create table a(id int,aa int)
create table b(id int,bb int)
create table c(id int,cc int)
insert into a
select 1,1 union all
select 2,2 union all
select 3,3 union all
select 4,4 union all
select 5,5
insert into b
select 1,1 union all
select 2,2 union all
select 7,7 union all
select 8,8
insert into c
select 5,5
select t.id as 产品编码, case when t.a_aa IS NULL then 0 else t.a_aa end as a进货量, case when t.b_bb IS NULL then 0 else t.b_bb end as b库存量, case when c.cc IS NULL then 0 else c.cc end as c销售量 from
(select a.aa as a_aa, b.bb as b_bb, ISNULL(a.id,b.id) as id from a full outer join b on a.id=b.id) t
full outer join c on t.id=c.id
-------------------------------------------------------------------------
--产品编码 a进货量 b库存量 c销售量
--1 1 1 0
--2 2 2 0
--3 3 0 0
--4 4 0 0
--5 5 0 5
--7 0 7 0
--8 0 8 0
select a.* ,
isnull(m.XiaoShouShuLiang, 0) XiaoShouShuLiang,
isnull(n.JinHuoShuLiang, 0) JinHuoShuLiang
from a left join
(select Name , BianMa , sum(XiaoShouShuLiang) XiaoShouShuLiang from b group by Name , BianMa) m
on a.Name = a.Name and a.BianMa = m.BianMa left join
(select Name , BianMa , sum(JinHuoShuLiang) JinHuoShuLiang from c group by Name , BianMa) n
on a.Name = a.Name and n.BianMa = n.BianMa
select a.* ,
isnull(m.XiaoShouShuLiang, 0) XiaoShouShuLiang,
isnull(n.JinHuoShuLiang, 0) JinHuoShuLiang
from a left join
(select Name , BianMa , sum(XiaoShouShuLiang) XiaoShouShuLiang from b group by Name , BianMa) m
on a.Name = a.Name and a.BianMa = m.BianMa left join
(select Name , BianMa , sum(JinHuoShuLiang) JinHuoShuLiang from b group by Name , BianMa) n
on a.Name = a.Name and n.BianMa = n.BianMa
select a.BianMa 商品编码,
isnull(b.value , 0) 销售 ,
isnull(c.value , 0) 进货 ,
isnull(c.value , 0) - isnull(b.value , 0) 库存
from a
left join b on a.BianMa = b.BianMa
left join c on a.BianMa = c.BianMa