Help 。求sql实现!!
时间:2011-11-29
来源:互联网
我要在一个事物中实现如下功能:
比如我有如下库存表
ID Count
1 2
2 3
3 5
我需要发货8个,要按照ID的从小到大的顺序发货。
先判断如果ID=1中的数量是否满足发货需求,如果ID=1中的数量小于8个。就发ID=1中存在的数量,剩余的数量从ID=2中发。如果ID=2也不满足,就发ID=2中存在的数量,剩余的数量从ID=3中发。直到发完所有的数量。
要实现以上的功能,能不能通过一条语句来实现。不要用存储过程来处理。
比如我有如下库存表
ID Count
1 2
2 3
3 5
我需要发货8个,要按照ID的从小到大的顺序发货。
先判断如果ID=1中的数量是否满足发货需求,如果ID=1中的数量小于8个。就发ID=1中存在的数量,剩余的数量从ID=2中发。如果ID=2也不满足,就发ID=2中存在的数量,剩余的数量从ID=3中发。直到发完所有的数量。
要实现以上的功能,能不能通过一条语句来实现。不要用存储过程来处理。
作者: jinxing71 发布时间: 2011-11-29
SQL code
--> --> (Roy)生成測試數據 if not object_id('Tempdb..#T') is null drop table #T Go Create table #T([ID] int,[Count] int) Insert #T select 1,2 union all select 2,3 union all select 3,5 Go select ID,[Count],DeliveryQty=Case when [Total]<=8 then [Count] else 8+[Count]-[Total] end from (Select * ,(select SUM([Count]) from #T where ID<=a.ID) as [Total] from #T as a )t where [Total]-[Count]<8 /* ID Count DeliveryQty 1 2 2 2 3 3 3 5 3 */
作者: roy_88 发布时间: 2011-11-29
写一个计算方法给你,在表上应该用一个列记录已发数量
作者: roy_88 发布时间: 2011-11-29
SQL code
Create table #T([ID] int,[Count] int) Insert #T select 1,2 union all select 2,3 union all select 3,5 select a.ID,a.Count, case when a.Subtotal >=0 then a.Subtotal else a.Count end Subtotal from ( select *,(select sum([Count])-8 from #T where [Count]<=t.[Count]) as Subtotal from #T t) a
作者: koumingjie 发布时间: 2011-11-29
SQL code
if object_id('tb','U') is not null drop table tb go create table tb ( id int, [count] int ) go insert into tb select 1,2 union all select 2,3 union all select 3,5 go update tb set [count]=case when (select sum([count]) from tb where id<=a.id)<8 then 0 else (select sum([count]) from tb where id<=a.id)-8 end from tb a select * from tb /* id count ----------- ----------- 1 0 2 0 3 2 (3 行受影响) */
作者: pengxuan 发布时间: 2011-11-29
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28