GROUP BY in SQL
GROUP BY splits rows into buckets and aggregates each bucket.
SELECT
country,
plan,
COUNT(*) AS customers,
SUM(monthly_total) AS mrr
FROM subscriptions
GROUP BY country, plan
ORDER BY mrr DESC;
How it works
- Every non-aggregated column must appear in the
GROUP BY. - You can group by more than one column for a cross tabulation.
- Ordering by the aggregate ranks the buckets.
Keywords and builtins used here
ASBYCOUNTDESCFROMGROUPORDERSELECTSUM
The run, in numbers
- Lines
- 8
- Characters to type
- 131
- Tokens
- 30
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 21 seconds.
Step 1 of 4 in Grouping, step 5 of 22 in Joins & aggregation.