Skip to content
Advertisement

How can I get the percentage of the sum of the top 5 countries in SQL?

I want to calculate the percentage of the sum of the top 5 countries by number of customers compared to the total number of customers. The SQL Editor rounds decimals, therefore the counter of my calculation needs to be multiplied by 100 before dividing it.

I have tried the following SQL statement:

Here is the table:
https://www.w3schools.com/sql/trysql.asp?filename=trysql_asc

Advertisement

Answer

Hmmm . . . This would use window functions and conditional aggregation:

Note that your code has SELECT * with GROUP BY. That is pretty close to blasphemy in SQL — it is a construct that generates an error in almost all databases. The unaggregated SELECT expressions need to be consistent with the GROUP BY expressions in an aggregation query.

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