求一条平分件数的SQL
declare @t table(id int,p int,g numeric(18,2),m numeric(18,2))
insert into @t(id,p,g,m)
select 1001,3,40.00,4.0 union all
select 1002,30,900.00,75.00 union all
select 1003,10,800.00,70.00
平分条件只有一个值 ,比如我输入: 2 想得到如下数据:
/*
groupName id p g m
----------- ----------- ----------- ----------- -----------
1 1001 3 40 4
1 1002 18 540 45
2 1002 12 360 30
2 1003 10 800 70
*/
BEGIN
SET @w = @p
WHILE @j <= @i
BEGIN
SET @p_new = @cnt / @i
IF @w<=0
BREAK
IF @w < @p_new
SET @p_new = @w
SET @g_new = @p_new * 1.0 / @p * @g
SET @m_new = @p_new * 1.0 / @p * @m
INSERT INTO @tb
VALUES (@id , @p_new , @g_new , @m_new)
SET @j = @j + 1
SET @w = @w - @p_new
END
FETCH NEXT FROM c INTO @id ,@p, @g,@m ;
END
CLOSE c ;
DEALLOCATE c ;
SELECT *
FROM @tb AS t
/*
idpgm
1001340.004.00
100310800.0070.00
100221630.0052.50
10029270.0022.50
*/