Count percentage of column with GROUP BY
-
02-03-2021 - |
题
Consider the following query:
SELECT
country
, count(id) AS "count"
FROM
lead
WHERE
date_part('year', lead.since) = date_part('year', CURRENT_DATE)
GROUP BY "country"
ORDER BY "count" DESC
;
It returns something like:
country count
fr 3456
us 569
sc 248
…
How can I add a third column with the percentage of the total count?
解决方案
SELECT country,
COUNT(id) "count",
COUNT(id) / SUM(COUNT(id)) OVER () * 100 percent
FROM lead
WHERE date_part('year', lead.since) = date_part('year', CURRENT_DATE)
GROUP BY country
ORDER BY "count" DESC;
不隶属于 dba.stackexchange