日期:2014-05-17  浏览次数:20501 次

sql 数量的计算
--物料表
if exists(select * from sysobjects where name= 'wlinfo')
drop table wlinfo
go
create table wlinfo
(
wlcode nvarchar(20) primary key,
wltype nvarchar(20),
wlname nvarchar(20),
wiunit nvarchar(20)
)
go
insert into wlinfo
select '001','成品','台式电脑','台' union all
select '001-001','半成品','显示器','台' union all
select '001-002','半成品','主机','台' union all

select '001-002-001','材料','CPU','个' union all
select '001-002-002','材料','主板','个' union all
select '001-002-003','材料','电源','个' union all
select '001-002-004','材料','内存','个'
go
--关系表
if exists(select * from sysobjects where name= 'relation')
drop table relation
go
create table relation
(
id int primary key identity(1,1),
wlcode nvarchar(20),
wlcode1 nvarchar(20)
)
insert into relation
select '001','001-001' union all
select '001','001-002' union all
select '001-002','001-002-001' union all
select '001-002','001-002-002' union all
select '001-002','001-002-003' union all
select '001-002','001-002-004'
go
--库存表
if exists(select * from sysobjects where name= 'wlinWM')
drop table wlinWM
go
create table wlinWM
(
id int primary key identity(1,1),
wlcode nvarchar(20),
wlnumber int
)
go
insert into wlinWM
select '001-001',2 union all
select '001-002-001',2 union all
select '001-002-002',3 union all
select '001-002-003',4 union all
select '001-002-004',5
go
select * from wlinfo
select * from relation
select * from wlinWM 
--听题,以上都是测试数据,如1台电脑= 1个显示器+1个主机
--1个主机= 1个CPU+1个主板+1个电源+1个内存
--现在
求:
1:半成品 数量 剩余材料 数量
2:成品 数量 半成品 数量 剩余材料 数量
SQL

------解决方案--------------------

with cte1 --半成品数量
as
(
select 
半成品=t2.wlcode,
半成品数量=MIN(t1.wlnumber)
from
wlinWM t1 
inner join wlinfo t2 on substring(t1.wlcode,0,8)=t2.wlcode
group by t2.wlcode
),
cte2 -- 剩余材料 数量
as
(
select 
剩余材料=t1.wlcode
,剩余材料数量=t1.wlnumber-t2.半成品数量
from
wlinWM t1
inner join cte1 t2 on substring(t1.wlcode,0,8)=t2.半成品
where
t1.wlnumber>t2.半成品数量
),
cte3 --成品 数量
as
(
select 
成品=substring(t1.半成品,0,4),
成品数量=MIN(t1.半成品数量)
from
cte1 t1
group by substring(t1.半成品,0,4)
)
select * from cte1 --半成品
union all
select&