Overview
Find the countries that bring in the most revenue: count and total orders with GROUP BY, and keep only the big groups with HAVING.
- COUNT(*) and SUM()
- GROUP BY one row per value
- HAVING filters groups
- ORDER BY ... DESC
Short Course
GROUP BY folds rows into one per value, and COUNT(*) or SUM() summarize
each group. Trap: WHERE filters rows before grouping, so a condition on a
count goes in HAVING.
SELECT country, COUNT(*) AS orders
FROM orders
GROUP BY country
HAVING COUNT(*) >= 2 -- WHERE COUNT(*) >= 2 is an error
ORDER BY orders DESC;
Task
Return each country with its number of orders and its revenue
(SUM(total)), only for countries with at least 2 orders, highest revenue
first. In the database below, France has 3 orders worth 120 in total.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | countryTEXT | totalREAL |
|---|---|---|
| 1 | FR | 50.0 |
| 2 | DE | 30.0 |
| 3 | FR | 40.0 |
| 4 | ES | 99.0 |
| 5 | DE | 25.0 |
| 6 | FR | 30.0 |
| 7 | IT | 200.0 |
| 8 | IT | 10.0 |
Test Suites
Pending
Next
Output