Postgresql

使用 GROUP BY 計算列的百分比

  • May 20, 2020

考慮以下查詢:

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
;

它返回如下內容:

country count
fr  3456
us  569
sc  248
…

如何添加佔總數百分比的第三列?

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;

引用自:https://dba.stackexchange.com/questions/267553