Skip to content
Advertisement

SQL relative percentage for each country

I have a table: maps_query like below:

The question is to output the relative percentage of queries for maps_query for each country.

Desired output is like below:

I don’t quite understand what relative percentage is here but I assumed it’s asking to output (a country’s search_query counts/ all search_query for all countries)?

Would something like the following work?

Advertisement

Answer

You almost have it. Here’s your SQL adjusted slightly:

The result, using some test data:

search_query wasn’t a numeric type. I think you meant query_score.

No need to multiply by 100, if your expected result is not a percent, but just the fraction between 0 and 1.

Your use of a window function wasn’t quite valid, since you tried to SUM OVER a non-aggregate (expression not functionally dependent on the GROUP BY terms).

I resolved that by using SUM(query_score) as the expression to use in the window function argument.

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