Question

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?

Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top