SQL 实际进销存应用求助
我现在有三个表:
表A:编号,库名,存量
P001,K1, 2
P002,K1, 3
P003,K2, 5
表B:编号,库名,进量
P001,K1, 5
P001,k2, 1
P003,K2, 6
P004,K2, 1
P004,K2, 1
表C:编号,库名,出量
P001,K1, 3
P001,K1, 1
P001,K2, 1
P004,K2, 1
P003,K2, 1
我想实现:
1、按编号汇总所有数量:
编号,存量,进量,出量
P001,2, 6, 5
P002,3, null, null
P003,4, 6, 1
P004 null,2, 1
2、库名=K2时:
编号,存量,进量,出量
P001,null, 1, 1
P002,null,null, null
P003,5 , 6, 1
P004 null, 2, 1
我目前的做法是使用临时表,然后把对应的数据插入。请问有没有更好的办法?谢谢!
------解决方案--------------------可以不用临时表啊,三表联合查询即可
------解决方案----------------------测试
declare @a table (bh varchar(10),cm varchar(10),qty int)
insert into @a
select 'P001','K1', 2 union all select
'P002','K1', 3 union all select
'P003','K2', 5
declare @b table (bh varchar(10),cm varchar(10),qty_in int)
insert into @b
select 'P001','K1', 5 union all select
'P001','k2', 1 union all select
'P003','K2', 6 union all select
'P004','K2', 1 union all select
'P004','K2', 1
declare @c table (bh varchar(10),cm varchar(10),qty_out int)
insert into @c
select 'P001','K1', 3 union all select
'P001','K1', 1 union all select
'P001','K2', 1 union all select
'P004','K2', 1 union all select
'P003','K2', 1
--查询1
select t1.bh 编号,t1.qty 存量,t2.qty_in 进量,t3.qty_out 出量
from @a t1
left join (select bh,sum(qty_in) qty_in from @b group by bh) t2 on t1.bh=t2.bh
left join (select bh,sum(qty_out) qty_out from @c group by bh) t3 on t1.bh=t3.bh
--查询2
select t1.bh 编号,t3.qty 存量,t1.qty_in 进量,t2.qty_out 出量
from (selec