I need some help writing a subquery. I have columns where I need to take a percentage of a population but based on some other column.
state | pop | column_a |
---|---|---|
nyc | 10 | 1 |
ny | 15 | 1 |
nyc | 20 | 0 |
ny | 25 | 0 |
I need to sum the populations by column_a equals 1 over the whole population based by state.
something like below is the desired outcome.
state | % |
---|---|
nyc | 50.0 |
ny | 37.5 |
I have tried window functions, subqueries (not my strength), I am not sure how to craft subquery.
-- numerator
select
state,
sum(population)
from table
where column_a = 1
group by state
order by state;
-- denominator
select
state,
sum(population)
from table
group by state
order by state;
This is as far I get, I am not sure how to combine these two queries to yield the table above.
2
Answers
This will work correctly where all states have values for both numerator and denominator.
In Postgresql you can filter element to sum with FILTER parameter. This way the query comes very simple.
This results: