SQL · Level 2 Aggregation

SQL GROUP BY and HAVING

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

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;

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

orders 8 rows
idINTEGERcountryTEXTtotalREAL
1FR50.0
2DE30.0
3FR40.0
4ES99.0
5DE25.0
6FR30.0
7IT200.0
8IT10.0
solution.sql
Test Suites Pending
Output