declare @a table(下单日期 smalldatetime, 物品名称 varchar(10), 下单数量 int)
insert @a select '07.2.10', '桌子', 200
union all select '07.3.15', '桌子', 30
union all select '07.3.20', '桌子', 200
union all select '07.3.25', '桌子', 110
union all select '07.3.10', '柜子', 120
union all select '07.3.12', '柜子', 180
union all select '07.3.12', '书', 50declare @b table(交货日期 smalldatetime, 物品名称 varchar(10), 交货数量 int)
insert @b select '07.2.10', '桌子',200
union all select '07.3.12', '桌子', 80
union all select '07.3.10', '柜子', 120
union all select '07.3.15', '柜子', 120select *,数量=(select sum(下单数量) from @a where 物品名称=a.物品名称 and 下单日期<=a.下单日期)from @a a
select 下单日期,AA.物品名称,下单数量 from
(select *,数量=(select sum(下单数量) from @a where 物品名称=a.物品名称 and 下单日期<=a.下单日期)from @a a) AA
where exists(select 1 from
(select 物品名称,sum(交货数量) 交货数量 from @b group by 物品名称) BB where 物品名称=AA.物品名称 and 交货数量<AA.数量)
union all
select * from @a a where not exists(select 1 from @b where 物品名称=a.物品名称 )