Skip to content

Instantly share code, notes, and snippets.

@danwakefield
Created February 6, 2024 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danwakefield/1d3e63ea5bf52eceb5a5687cce5e6b7e to your computer and use it in GitHub Desktop.
Save danwakefield/1d3e63ea5bf52eceb5a5687cce5e6b7e to your computer and use it in GitHub Desktop.
-- The args being numeric cause auto casting; This is what we want
-- e.g `COUNT(*)` returns a whole number but we often want to divide it to float
-- Postgres percent function
CREATE OR REPLACE FUNCTION percent(portion numeric, total numeric, round_level integer default 1)
RETURNS numeric
IMMUTABLE
RETURNS NULL ON NULL INPUT
PARALLEL SAFE
as $fbd$
select
CASE
WHEN total = 0 THEN 0
ELSE ROUND(100 * (portion / total), round_level)
END
$fbd$ language sql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment