|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册账号
×
---------------------------------
-- Author:
-- Date :
---------------------------------
--> 生成测试数据表:销售订单
If not object_id('[销售订单]') is null
Drop table [销售订单]
Go
Create table [销售订单]([日期] Datetime,[料号] nvarchar(1),[数量] decimal(18,2),[状态] nvarchar(3))
Insert 销售订单
Select '2009-09-27','A','2000','已下单'
Go
--> 生成测试数据表:存货表
If not object_id('[存货表]') is null
Drop table [存货表]
Go
Create table [存货表]([日期] Datetime,[料号] nvarchar(1),[数量] decimal(18,2),[状态] nvarchar(4))
Insert 存货表
Select '2009-08-10','B','1000','现有库存'
Go
--> 生成测试数据表:bom_a
If not object_id('[bom_a]') is null
Drop table [bom_a]
Go
Create table [bom_a]([parentno] nvarchar(1),[qty] decimal(18,2),[unit] nvarchar(3))
Insert bom_a
Select 'A',1.0,'pcs' union all
Select 'B',1.0,'pcs'
Go
--Select * from bom_a
--> 生成测试数据表:bom_b
If not object_id('[bom_b]') is null
Drop table [bom_b]
Go
Create table [bom_b]([parentno] nvarchar(1),[childno] nvarchar(1),[qty] decimal(18,2),[unit] nvarchar(3))
Insert bom_b
Select 'A','B',2.0,'pcs' union all
Select 'A','C',3.0,'G' union all
Select 'B','C',1.0,'G' union all
Select 'B','D',2.0,'G'
Go
--Select * from bom_b
/*
A(1PCS)
__|__
| |
B(2PCS) C(3G)
__|__
| |
C(1G) D(2G)
*/
-->SQL查询如下:
;with t as
(
select [childno] 主料号,*,qty as xs--,0 as lvl
from (
select null as parentno,[parentno] as childno,[qty],[unit] from bom_a
union all
select * from bom_b
) as tb
where childno='A'
union all
select b.主料号,a.*,b.qty--,b.lvl+1
from (
select null as parentno,[parentno] as childno,[qty],[unit] from bom_a
union all
select * from bom_b
) as a join t as b on a.[parentno]=b.[childno]
), t1 as
(
select 主料号,childno 料号,sum(qty*xs) as auxqty,unit
from t
group by 主料号,childno,unit
)
select a.料号,需求数=cast(a.auxqty*b.数量-isnull(c.数量,0) as dec(18,2)),a.unit 单位
from t1 a
join [销售订单] b
on a.主料号=b.料号 and a.料号<>b.料号
left join [存货表] c
on a.料号=c.料号
/*
料号 需求数 单位
---- --------------------------------------- ----
B 3000.00 pcs
C 10000.00 G
D 8000.00 G
(3 行受影响)
*/ |
|