--建表
create table table1
(
item varchar(4),
date datetime,
plancount int,
finishcount int
)
insert into table1 select 'A001', '2006-11-1', 1000, 2500
insert into table1 select 'A001', '2006-11-8', 1000, 2500
insert into table1 select 'A001', '2006-11-22', 1500, 2500
--语句
select item,date,plancount,
case when finishcount - sum1 >= plancount
then plancount
else case when finishcount > sum1
then finishcount - sum1
else 0
end
end as finish
from
(select *,sum1 = (select isnull(sum(plancount),0) from table1 where date < t1.date)
from table1 t1)a
----稍微改动一点
--语句
select item,date,plancount,
case when finishcount - sum1 >= plancount
then plancount
else case when finishcount > sum1
then finishcount - sum1
else 0
end
end as finish
from
(select *,sum1 = (select isnull(sum(plancount),0)
from table1 where item = t1.item and date < t1.date)
from table1 t1)a