+ -
当前位置:首页 → 问答吧 → Help 。求sql实现!!

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中发。直到发完所有的数量。
要实现以上的功能,能不能通过一条语句来实现。不要用存储过程来处理。

作者: 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

热门下载

更多