Home > Software engineering >  SQL Sum with multiple conditions and join
SQL Sum with multiple conditions and join

Time:07-20

I have a table like this below:

date, country, session

May I know how to sum up all the sessions based on the country and get the top 5 results?

The result will be something like this below:

Malaysia, 9000 Singapore, 8000 Brunei, 7000 Indonesia, 6000 Vietnam, 5000

CodePudding user response:

SELECT COUNT(country) as sessionsCount , country 
FROM sessions 
GROUP BY country 
ORDER BY sessionsCount DESC 
LIMIT 5

The COUNT() function returns the number of rows that matches a specified criterion.

The ORDER BY keyword is used to sort the result-set in ascending or descending order. To sort the records in descending order, use the DESC keyword.

The LIMIT clause is used to specify the number of records to return.

  • Related