Created
April 18, 2022 20:41
-
-
Save mhseiden/b114c3606a7122a9a379bc5591cf7eca to your computer and use it in GitHub Desktop.
A few different SQL approaches for calculating a percent of total.
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
-- 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