How do I summarize rows by category with GROUP BY?
Quick answer
Use GROUP BY on the category column and an aggregate such as SUM on the numeric column: SELECT category, SUM(quantity) AS total_quantity FROM inventory GROUP BY category;. Each distinct category produces one result row, with the sum calculated from the rows in that group. If you select another descriptive column, include it in the grouping or aggregate it intentionally.
The question, the details, the next step.
A practical checklist
Replace
inventory,category, andquantitywith the names in your table.Use
SUMfor totals; use a different aggregate only if it matches the question you are answering.Group by every descriptive field you intend to show as part of each result row.
Check whether filters exclude rows that should be included in the totals.
Verify one example category by adding its contributing rows.
A few more useful answers
What if I want totals by category and location?
Select both category and location, then group by both. Each distinct category-location combination will have its own result row and total.
Why does SQLite allow a selected column that is not grouped or aggregated?
SQLite permits this as an extension, but the bare column's value may come from an arbitrary row in its group. Include the column in GROUP BY or aggregate it intentionally; other database engines may apply stricter rules. [S1]
Sources
References used for this guide.
- [S1] SQLite SELECT — GROUP BY, aggregates, and bare columns sqlite.org · Checked
