2

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?

1 Answer 1

5
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;
2
  • what does SUM(COUNT(id)) OVER() do in this case? I find it hard to understand.
    – jdhao
    Sep 29, 2023 at 13:09
  • @jdhao COUNT(id) counts id values with current GROUP BY expression. SUM(COUNT(id)) OVER() gets the sum of these values over the whole output rowset - i.e. it counts total count for all id values.
    – Akina
    Sep 29, 2023 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.