DECLARE @valueToDistribute float;
SET @valueToDistribute = 100;
DECLARE @rest int;
DECLARE @temp int;
SET @temp = 0;
DECLARE @error float
SET @error = 0;
DECLARE @tableToDistribute table
(
id int
,MaxValue int
,InitialValue int
,DistributedValue int
);
INSERT @tableToDistribute values(1, 0, 0, 0);
INSERT @tableToDistribute values(2, 0, 0, 0);
INSERT @tableToDistribute values(3, 0, 0, 0);
INSERT @tableToDistribute values(4, 0, 0, 0);
INSERT @tableToDistribute values(5, 0, 0, 0);
INSERT @tableToDistribute values(6, 0, 0, 0);
--INSERT @tableToDistribute values(7, 0, 0, 0);
--INSERT @tableToDistribute values(8, 0, 0, 0);
--INSERT @tableToDistribute values(9, 0, 0, 0);
SET @rest = @valueToDistribute;
WITH Count_CTE (Id, [Percent], MaxId)
AS
(
SELECT
Id
, [Percent] = CAST(@valueToDistribute / (SELECT COUNT(*) FROM @tableToDistribute) / 100.00 as float)
, [MaxId] = (SELECT MAX(Id) FROM @tableToDistribute)
FROM @tableToDistribute
)
UPDATE t
SET
@error = @error + (cte.[Percent] * @valueToDistribute) - ROUND(cte.[Percent] * @valueToDistribute, 0)
,@temp =
case
when ROUND(@error, 5) <> 0.00000
then
case
when t.Id = cte.MaxId then @rest --ROUND(cte.[Percent] * @valueToDistribute, 0) + FLOOR(@error)
else ROUND(cte.[Percent] * @valueToDistribute, 0)
end
else ROUND(cte.[Percent] * @valueToDistribute, 0)
end
,DistributedValue = @temp
,@rest = @rest - @temp
FROM @tableToDistribute t
inner join Count_CTE cte on t.Id = cte.Id;
SELECT
*
FROM @tableToDistribute