Grouping on several columns in SQL
Group by two columns and every distinct pair becomes a row.
SELECT
country,
plan,
COUNT(*) AS customers,
ROUND(AVG(monthly_total), 2) AS avg_bill
FROM subscriptions
GROUP BY country, plan
HAVING COUNT(*) >= 5
ORDER BY country, customers DESC;
How it works
- The grouped columns are the only ones you may select unaggregated.
- Ordering by the grouped columns makes the report readable.
- Add a column to
GROUP BYand the counts get smaller, never larger.
Keywords and builtins used here
ASAVGBYCOUNTDESCFROMGROUPHAVINGORDERSELECT
The run, in numbers
- Lines
- 9
- Characters to type
- 182
- Tokens
- 45
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 32 seconds.
Step 2 of 4 in Grouping, step 6 of 22 in Joins & aggregation.