So, I feel the need to be recorded, so that after the encounter this problem again, and get answers from the idea.
sql cycle taking the difference, how to write?
http://bbs.csdn.net/topics/390636438?page=1#post-396012416
There are a set of conditions and a number (such as 10)
can detect a plurality of data depending on conditions such as the appearance is so
ID NumOut the Num
. 1. 4 0
2. 5 0
. 3 0. 8
. 4. 6 0 ......
Num subtracting the numbers in order with each record, enough to reduce a difference NumOut assigned, not reduced, the same assignment NumOut Num, then a Save the remaining number.
In other words, the above data is updated to:
ID the Num NumOut
1 4 4
2 5 5
3 1 8
4 6 0 ......
This should be how to express sql statement? ? ?
According to my ideas should write cycles judgment, but never written cycle sql, check out the data, how you should save it? Urgently, thank advise it! ! !
Here is my solution:
-
--drop table tb
-
-
create
TABLE tb (
ID
int,
Num
int,NumOut
int)
-
INSERT
into tb
-
SELECT
1,
4,
0
UNION ALL
-
SELECT
2,
5,
0
UNION ALL
-
SELECT
3,
8,
0
UNION ALL
-
SELECT
4,
6,
0
-
go
-
-
-
--你要减的数
-
declare @
num
int
-
-
set @
num =
10
-
-
;with t
-
as
-
(
-
select *,
-
row_number()
over(
order
by @@servername)
as
rownum
-
from tb
-
),
-
-
tt
-
as
-
(
-
select
id,
-
num,
-
numout,
-
(
select
sum(
num)
from t t2
-
where t2.rownum <= t1.rownum)
as sum_num
-
from t t1
-
)
-
-
--更新
-
update tt
-
set numout =
case
when sum_num <= @
num
-
then
num
-
when sum_num > @
num
and
-
@
num - (sum_num -
num) >=
0
-
then @
num - (sum_num -
num)
-
else
0
-
end
-
-
-
--查询
-
select *
from tb
-
/*
-
ID Num NumOut
-
1 4 4
-
2 5 5
-
3 8 1
-
4 6 0
-
*/