这是先进先出计算利润的方法,看下有没有参考价值:
select identity(int,1,1) ID,* into #1 from Tin order by 品种,时间
select 品种,sum(数量) 数量 into #2 from Tout group by 品种
select 品种,sum(数量) 数量,sum(数量*价格) 金额
from (
select a.品种,
(case when (select sum(数量) from #1 where ID<=
a.ID and 品种=a.品种)<= b.数量 then 0 else
(case when (select isnull(sum(数量),0) from #1 where ID<
a.ID and 品种=a.品种)<= b.数量 then
(select sum(数量) from #1 where ID<=
a.ID and 品种=a.品种)-b.数量 else a.数量 end) end) 数量,
价格
from #1 a,#2 b
where a.品种=b.品种) a
group by 品种