Skip to content

Instantly share code, notes, and snippets.

@mhseiden
Created April 18, 2022 20:41
Show Gist options
  • Save mhseiden/b114c3606a7122a9a379bc5591cf7eca to your computer and use it in GitHub Desktop.
Save mhseiden/b114c3606a7122a9a379bc5591cf7eca to your computer and use it in GitHub Desktop.
A few different SQL approaches for calculating a percent of total.
-- A percent of total calculation using a joined, aggregated subquery
select state
, county
, 100 * population / state_population as pct_state_population
from census
join (select state, sum(population) state_population from census group by 1) using (state)
;
-- A percent of total calculation using a windowed aggregate
select state
, county
, sum(population) over (partition by state) state_population
, 100 * population / state_population as pct_state_population
from census
;
-- A percent of total calculation using a correlation in the SELECT list
select state
, county
, (select sum(population) from census i where o.state = i.state) state_population
, 100 * population / state_population as pct_state_population
from census o
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment