我有一些数据如下;
select * into #temp from (
select getdate() Dt,20 Qt
union all
select getdate()-1 Dt,70 Qt
union all
select getdate()-1 Dt,20 Qt
union all
select getdate()-2 Dt,50 Qt
union all
select getdate()-4 Dt,40 Qt
union all
select getdate()-4 Dt,80 Qt
union all
select getdate()-6 Dt,20 Qt
) a
此数据是针对特定日期每次批量生产的产品数量。在任何时候,我只能发货数量 < 100,并且也可以按批处理发货。因此,如果计数超过 100,发货数量就会超过,输出应如下所示
date QT shipnum
2016-11-25 03:45:45.897 20 1
2016-11-27 03:45:45.897 40 1
2016-11-27 03:45:45.897 80 2
2016-11-29 03:45:45.897 50 3
2016-11-30 03:45:45.897 70 4
2016-11-30 03:45:45.897 20 4
2016-12-01 03:45:45.897 20 5
可以使用 CTE 来实现此目的吗?否则,如何实现这一点
最佳答案
您使用的是什么版本?
你能试试这个脚本吗:
SELECT *,SUM(qt)OVER(ORDER BY rn) AS [sum],SUM(qt)OVER(ORDER BY rn)/100+1 AS shipnum FROM (
SELECT *,ROW_NUMBER()OVER(ORDER BY dt) AS rn FROM #temp
) t
Dt Qt rn sum shipnum ----------------------- ----------- -------------------- ----------- ----------- 2016-11-25 17:29:16.280 20 1 20 1 2016-11-27 17:29:16.280 40 2 60 1 2016-11-27 17:29:16.280 80 3 140 2 2016-11-29 17:29:16.280 50 4 190 2 2016-11-30 17:29:16.280 70 5 260 3 2016-11-30 17:29:16.280 20 6 280 3 2016-12-01 17:29:16.280 20 7 300 4
关于SQL 满足以下要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40906204/