geozelot
geozelot

Reputation: 557

PostgreSQL - Create randomized percentages?

For testing purposes I need to create a JSONB object with n random percentages, so that they sum up to 1.0.

Obviously, the very simple

SELECT jsonb_object(array_agg(ARRAY['prefix_' || n::TEXT, round(random()::NUMERIC, 2)::TEXT])) AS e
FROM   generate_series(1,8) AS n
;

will produce numbers that won't sum up to 1.0.

I expect the solution to be much more complicated, and I can't seem to put my head around this.

How to do this in PostgreSQL 10?

Upvotes: 0

Views: 73

Answers (1)

Laurenz Albe
Laurenz Albe

Reputation: 246403

You just have to adjust the values.

You could base your generator on this query:

WITH r AS (
   SELECT random()
   FROM generate_series(1, 8)
)
SELECT random/sum(random) OVER ()
FROM r;

Upvotes: 1

Related Questions