I have a question for all the SQL experts.
There is table looking like:
clanname country points
name1 country1 100
name2 country1 90
name3 country1 10
name4 country2 100
name5 country2 80
name6 country2 70
I would like to make a country ranking involving only the top2 results of each country. so, in this example, the ranking should be:
country average-points
country2 95
country1 90
If there a way to get this result with only one SQL query using subqueries?
In reality, I have more than 200 countries.. and thousands of results for each country. But I'd like to filter only the top 30 results of each country.
Right now I managed to get the average of one country using this query:
SELECT
location, AVG(warswon)
FROM
(SELECT
`name`, `location`, `warswon`
FROM
`clans`
WHERE
location = 'China'
ORDER BY
`clans`.`warswon` DESC
LIMIT 30) AS top30ofcountry
but how do I get the average results of each country in one query?
Is this possible?
GROUP BY locationROW_NUMBER() OVER (PARTITION BY country ORDER BY points DESC) AS RNin a sub query or CTE. Then, group by the countryWHERE RN <=your cutoff.