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

SQL 实际进销存应用

2013-04-05 
SQL 实际进销存应用求助我现在有三个表:表A:编号,库名,存量   P001,K1,2P002,K1,3P003,K2,5表B:编号,库名,

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 (select bh,cm,sum(qty_in) qty_in from @b group by bh,cm) t1  


left join (select bh,cm,sum(qty_out) qty_out from @c group by bh,cm) t2 on t1.bh=t2.bh and t2.cm='K2'
full join  @a t3 on t1.bh=t3.bh and t3.cm='K2'  
where t1.cm='K2'
union all
select t.bh 编号,null 存量,null 进量,null 出量 from @a t
where not exists(select 1 from @c where bh=t.bh and cm='K2')
order by t1.bh

/*
编号存量进量出量
P001265
P0023NULLNULL
P003561

编号存量进量出量
P001NULL11
P002NULLNULLNULL
P003561
P004NULL21
*/
[解决办法]

引用:
不需要。
第1个FULL JOIN ON A.编号=B.编号,第2个FULL JOIN ON A.编号=C.编号,应该包含了三个表中任何一个表有数据的记录。第2个FULL JOIN用ON B.编号=C.编号也可以,我觉得不需要ON A.编号=C.编号 OR B.编号=C.编号


我之前写过,如果不加“OR B.编号=C.编号”,那A中没有,而B、C中有,会变成两条记录(B一条,C一条);如果加上了,就是一条记录。
[解决办法]
引用:
引用:不需要。
第1个FULL JOIN ON A.编号=B.编号,第2个FULL JOIN ON A.编号=C.编号,应该包含了三个表中任何一个表有数据的记录。第2个FULL JOIN用ON B.编号=C.编号也可以,我觉得不需要ON A.编号=C.编号 OR B.编号=C.编号

我之前写过,如果不加“OR B.编号=C.编号”……


我想明白了,You are right. 可以用“ON ISNULL(A.编号,B.编号)=C.编号”吗?

热点排行
Bad Request.