Search code examples
sqlmysql

Sum a column and group it, then divide by a field in another table


I have two tables, one that looks like this:

Lis of companies and revenue

The other has the countries' populations:

enter image description here

I would like to sum up the revenue by country (I know how to do this part, e.g Select Sum(Revenue), Country from COMPANIES GROUP BY Country;)

and then divide it by the population from the other table to get per capital revenue , so the final result should be

enter image description here


Solution

  • If you have this set: sql_mode=only_full_group_by

    Then it will need to be like this:

    SELECT companies.country, 
           round(sum(revenue) / country.population, 2) as RevPerCap  
    FROM companies
    join country on country.name = companies.country  
    group by companies.country, country.population