sql problem more difficult to appear in the forum: 32 (row_number function + sql subquery cycle taking the difference)

Original: sql problem more difficult to appear in the forum: 32 (row_number function + sql subquery cycle taking the difference)

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:


  
  
  1. --drop table tb
  2. create TABLE tb ( ID int, Num int,NumOut int)
  3. INSERT into tb
  4. SELECT 1, 4, 0 UNION ALL
  5. SELECT 2, 5, 0 UNION ALL
  6. SELECT 3, 8, 0 UNION ALL
  7. SELECT 4, 6, 0
  8. go
  9. --你要减的数
  10. declare @ num int
  11. set @ num = 10
  12. ;with t
  13. as
  14. (
  15. select *,
  16. row_number() over( order by @@servername) as rownum
  17. from tb
  18. ),
  19. tt
  20. as
  21. (
  22. select id,
  23. num,
  24. numout,
  25. ( select sum( num) from t t2
  26. where t2.rownum <= t1.rownum) as sum_num
  27. from t t1
  28. )
  29. --更新
  30. update tt
  31. set numout = case when sum_num <= @ num
  32. then num
  33. when sum_num > @ num and
  34. @ num - (sum_num - num) >= 0
  35. then @ num - (sum_num - num)
  36. else 0
  37. end
  38. --查询
  39. select * from tb
  40. /*
  41. ID Num NumOut
  42. 1 4 4
  43. 2 5 5
  44. 3 8 1
  45. 4 6 0
  46. */

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12020062.html