Get percentage of group by
WITH number_of_tickets AS (
SELECT user_id, COUNT(user_id) AS number_of_tickets_per_user
FROM tickets
GROUP BY user_id
),
total_tickets AS (
SELECT SUM(number_of_tickets_per_user) total_tickets
FROM number_of_tickets
)
SELECT
user_id,
number_of_tickets_per_user,
ROUND(number_of_tickets_per_user / total_tickets,3) percent
FROM number_of_tickets, total_tickets;
I would suggest to use window functions:
SELECT DISTINCT user_id,
(count(*) over (partition by user_id) / count(*) over ()::numeric)
FROM tickets
ORDER BY user_id;
user_id | ?column?
---------+------------------------
1 | 0.06666666666666666667
2 | 0.06666666666666666667
3 | 0.20000000000000000000
4 | 0.66666666666666666667
(4 rows)