Skip to content
Advertisement

SQL: Joining tables and dividing each cell by match cell in another table?

Here is my population dataset detailing the population of each state through 2010 – 2019:

Population Data set

Here is my consumer complaints dataset which has date received and state:

Consumer complaints Data set

I already have the complaints for each state per year:

State per Year

I know I need to join compltsbypear and uspop on state and divide 2011(from complaints) / 2011 from uspop, etc for each match year.

How do I write the query that shows the states and for each year, the ratio of complaints to population?

Advertisement

Answer

I would approach this by unpivoting the population data, so there is one row per state and year. Then aggregate the complaints and join.

Your code looks like SQL Server, so I will use those conventions:

This produces the results you want in a perfectly reasonable format of one row per state/year. If you want it in a different format, you seem to be aware of how to pivot the data.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement