求数量分批SQL

wdsimon 2006-11-25 10:53:51
表table1数据如下
ITEM 日期 计划生产量 完成总量
A001 2006-11-1 1000 2500
A001 2006-11-8 1000 2500
A001 2006-11-22 1500 2500

查询需得到如下结果
ITEM 日期 计划生产量 已完成量
A001 2006-11-1 1000 1000
A001 2006-11-8 1000 1000
A001 2006-11-22 1500 500

就是要把总量按日期先后分配到每天.

...全文
182 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
冷箫轻笛 2006-11-25
  • 打赏
  • 举报
回复
--建表
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

--结果
A001 2006-11-01 00:00:00.000 1000 1000
A001 2006-11-08 00:00:00.000 1000 1000
A001 2006-11-22 00:00:00.000 1500 500
wdsimon 2006-11-25
  • 打赏
  • 举报
回复
UP
xluzhong 2006-11-25
  • 打赏
  • 举报
回复
----稍微改动一点
--语句
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

34,593

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧