PostgreSQL:如何正确计算百分比?

时间:2020-11-04 02:03:41

标签: sql postgresql

通过这个非常简单的查询,我获得了电影的总数(总数)和流派 从我的数据库。

select genre,count(*) from titles group by genre order by count desc;
     genre       | count 
-----------------+-------
 Drama           |   529
 Comic           |   393
 Martial arts    |   276
 History         |   269
 Action          |   237

我的问题是:如何获得百分比? 我想要这样的东西

select ??????;
     genre       | percentage 
-----------------+-------
 Drama           |   30%
 Comic           |   20%
 Martial arts    |   20%
 History         |   15%
 Action          |   11%
 Other           |   4%

在询问之前,我已经尝试了很多从gogle和stackexchange获取的代码,正如您从此psql历史记录中所看到的 但都会因错误或非常奇怪的结果而失败。

SELECT
    title,
    ROUND( AVG( genre ), 2 ) percentage
FROM
    titles
INNER JOIN genre
        USING(id_genre)
GROUP BY
    title
ORDER BY
    genre DESC;


select title, round ( AVG( genre ), 2 ) percentage from titles;


SELECT round((count(genre) *100)::numeric / NULLIF(count(*), 0), 2) AS percentage;

2 个答案:

答案 0 :(得分:2)

使用窗口功能:

select genre,
       count(*) as cnt,
       count(*) * 1.0 / sum(count(*)) over ()
from titles
group by genre
order by cnt desc

答案 1 :(得分:0)

感谢戈登的正确答案,使用此字符串,我获得了理想的结果(除了0%的结果是0.0001 ...通过舍入函数舍入,但这不是问题)

select genre, count(*) as total, round(count(*) * 100 / sum(count(*)) over ()) || ' %' as percent from titles group by genre order by total desc;

     genre       | total  | percent 
-----------------+--------+-------------
 Drama           |    529 | 17 %
 Comic           |    393 | 13 %
 Martial arts    |    276 | 9 %
 History         |    269 | 9 %
 Action          |    237 | 8 %

...