Created
February 6, 2024 20:54
-
-
Save danwakefield/1d3e63ea5bf52eceb5a5687cce5e6b7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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