HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Get percentage of group by

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
getpercentagegroup

Problem

I have this data:

CREATE TABLE tickets(user_id int NOT NULL);
INSERT INTO tickets VALUES (1);
INSERT INTO tickets VALUES (2);
INSERT INTO tickets VALUES (3); -- 3 times
INSERT INTO tickets VALUES (4); -- 10 times


Now I want to display the percentage of the number of tickets per user.

I tried this:

WITH number_of_tickets AS (
  SELECT user_id, COUNT(user_id) AS number_of_tickets_per_user
  FROM tickets 
  GROUP BY user_id
)
SELECT 
  number_of_tickets_per_user, 
  ROUND((COUNT(user_id) * 100.0) / (SELECT COUNT(DISTINCT(user_id)) FROM tickets), 3) -- No no no no
FROM number_of_tickets
GROUP BY number_of_tickets_per_user
ORDER BY number_of_tickets_per_user;


But I probably don't handle the percentage calculation well. The result always shows me 25% for each of the number of tickets per user.

Solution

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)

Code Snippets

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)

Context

StackExchange Database Administrators Q#216193, answer score: 9

Revisions (0)

No revisions yet.