I assume that the reason you want to exclude the subquery is to not double check the user table. Remember that the sum is the sum of the calculations for each country.
WITH c AS (SELECT country_id, count(*) AS cnt FROM users WHERE cond1=... GROUP BY country_id) SELECT *, 100.0*cnt/(SELECT sum(cnt) FROM c) AS percent FROM c;
This request creates a small CTE with statistics for each country. It will only scan the user table once and create a small result set (only one row for each country).
The sum (SELECT sum (cnt) FROM c) is calculated only once on this small result set, so it uses little time.
You can also use the window function:
SELECT country_id, cnt, 100.0*cnt/(sum(cnt) OVER ()) AS percent FROM (SELECT country_id, count(*) as cnt from users group by country_id) foo;
(this is the same as a nightwolf request with lol errors removed)
Both requests take the same time.
source share