日期:2014-05-18  浏览次数:20550 次

求一个SQL语句!(对我有点难!请各位大虾指点)
我有一个表,结构如下
ID,     RMONEY
1,       200
2,       300
3,       150
4,       700
要求能根据一给定的数值,按ID顺序和RMONET数值插入一新表,如给定600,则插入另一个表的记录为
ID,     NMONEY
1,       200
2,       300
3,       100
以上合计为600
如此类推,最好不要用游标!
各位是否有好办法,请指点!

------解决方案--------------------


create proc Testxx
@s decimal(10,0)
as

declare @i int
declare @y decimal(10,0)


declare @a table(ID int, RMONEY decimal(10,0) )
insert @a select 1, 200
union all select 2, 300
union all select 3, 150
union all select 4, 700
union all select 5, 800

set @i=0
set @y=0
select @y=case when @y> @s then @y else @y+rmoney end,@i=case when @y> @s then @i else @i+1 end from @a order by id

select id=identity(int,1,1), * into NewTable from
(
select rmoney from @a where id <=@i
union all
select min(@s)-sum(rmoney) from @a where id <=@i
) a
select * from Newtable
drop table newtable
=====================================
testxx 300
------解决方案--------------------
Create Table TEST
(ID Int,
RMONEY Int)
Insert TEST Select 1, 200
Union All Select 2, 300
Union All Select 3, 150
Union All Select 4, 700

Create Table TempTable
(ID Int,
RMONEY Int)
GO
Declare @RMONEY Int
Select @RMONEY = 600
Insert
TempTable
Select
B.ID,
(Case When B.SUMRMONEY + B.RMONEY > @RMONEY Then @RMONEY - B.SUMRMONEY Else B.RMONEY End) As RMONEY
From
(Select A.*, IsNull((Select SUM(RMONEY) From TEST Where ID < A.ID), 0) As SUMRMONEY From TEST A) B
Where @RMONEY > B.SUMRMONEY

Select * From TempTable
GO
Drop Table TEST, TempTable
--Result
/*
ID RMONEY
1 200
2 300
3 100
*/