PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Calculando porcentagens com a consulta GROUP BY

WITH t1 AS 
 (SELECT User, Rating, Count(*) AS n 
  FROM your_table
  GROUP BY User, Rating)
SELECT User, Rating, n, 
       (0.0+n)/(COUNT(*) OVER (PARTITION BY User)) -- no integer divide!
FROM t1;

Ou
SELECT User, Rating, Count(*) OVER w_user_rating AS n, 
        (0.0+Count(*) OVER w_user_rating)/(Count(*) OVER (PARTITION BY User)) AS pct
FROM your_table
WINDOW w_user_rating AS (PARTITION BY User, Rating);

Gostaria de ver se um desses ou outro rende um plano de consulta melhor com a ferramenta apropriada para o seu RDBMS.