Choose x random number having sum n on Sql server

How can I generate a random number x to have sum = n Example:

N=5000 x=5
1- 1500
2- 500
3- 700
4- 1400
5- 900
+4
source share
2 answers

Try this query:

DECLARE @x int, @N int, @num int
SET @X=5
SET @N=5000

CREATE TABLE #temp (chosen int)

WHILE @N>=0 and @X>0
BEGIN
    SET @num =RAND()*@N
    INSERT INTO #temp (chosen)
    SELECT CASE WHEN @X=1 THEN @N ELSE @num END AS Chosen
    SET @N=@N-@num
    SET @X=@X-1

END
SELECT chosen FROM #temp
DROP TABLE #temp
+3
source

All Articles