27,579
社区成员
发帖
与我相关
我的任务
分享
if object_id('tempdb..#tab') is not null drop table #tab
if object_id('tempdb..#Tab2') is not null drop table #Tab2
Create table #Tab(
[物料] varchar(50),
[数量] int,
)
Create table #Tab2(
[物料] varchar(50),
[数量] int,
[入库日期] datetime
)
INSERT INTO #tab
select 'A001',200 union all
select 'A001',1000 union all
select 'A001',1800 union all
select 'A002',200 union all
select 'A002',600
INSERT INTO #tab2
select 'A001',200,'2019/01/01' union all
select 'A001',400,'2019/01/02'union all
select 'A001',800,'2019/01/06' union all
select 'A002',100,'2019/01/08' union all
select 'A002',100,'2019/01/09'
;
with list1 as(
select *,endqty=case when lead([数量])over (partition by [物料] order by [入库日期]) is null then 999999999999999999999
else sum([数量])over(partition by [物料] order by [入库日期])
end
,startqty=sum([数量])over(partition by [物料] order by [入库日期])-[数量]
from #tab2
),list2 as(
select *,sumqty=sum([数量])over(partition by [物料] order by [数量] ) - [数量]
from #tab
)
select a.[物料],a.[数量],b.入库日期 --,B.*
from list2 a
left join list1 b on a.物料=b.物料 and a.[数量] > b.startqty and a.[数量]<=b.endqty
物料 数量 入库日期
-------------------------------------------------- ----------- -----------------------
A001 200 2019-01-01 00:00:00.000
A001 1000 2019-01-06 00:00:00.000
A001 1800 2019-01-06 00:00:00.000
A002 200 2019-01-09 00:00:00.000
A002 600 2019-01-09 00:00:00.000
Create table #Tab(
[物料] varchar(50),
[数量] int,
)
Create table #Tab2(
[物料] varchar(50),
[数量] int,
[入库日期] datetime
)
INSERT INTO #tab
select 'A001',200 union all
select 'A001',1000 union all
select 'A001',1800 union all
select 'A002',200 union all
select 'A002',600
INSERT INTO #tab2
select 'A001',200,'2019/01/01' union all
select 'A001',400,'2019/01/02'union all
select 'A001',800,'2019/01/06' union all
select 'A002',100,'2019/01/08' union all
select 'A002',100,'2019/01/09'
;
with list1 as(
select *,endqty=case when lead([数量])over (partition by [物料] order by [入库日期]) is null then 999999999999999999999
else sum([数量])over(partition by [物料] order by [入库日期])
end
,startqty=sum([数量])over(partition by [物料] order by [入库日期])-[数量]
from #tab2
),list2 as(
select *,sumqty=sum([数量])over(partition by [物料] order by [数量] ) - [数量]
from #tab
)
select a.[物料],a.[数量],b.入库日期 --,B.*
from list2 a
left join list1 b on a.物料=b.物料 and a.[数量] between b.startqty and b.endqty
物料 数量 入库日期
-------------------------------------------------- ----------- -----------------------
A001 200 2019-01-01 00:00:00.000
A001 1000 2019-01-01 00:00:00.000
A001 1800 2019-01-01 00:00:00.000
A002 200 2019-01-09 00:00:00.000
A002 600 2019-01-09 00:00:00.000