GROUP BY with Aggregate Functions

Uses GROUP BY with multiple aggregate functions to summarize sales data by category, including count, sum, average, min, and max calculations.

SqlData Fetching

Code

snippet
SELECT
    p.category_id,
    cat.category_name,
    COUNT(*) AS product_count,
    SUM(oi.quantity) AS total_units_sold,
    SUM(oi.quantity * oi.unit_price) AS total_revenue,
    AVG(oi.unit_price) AS avg_unit_price,
    MIN(oi.unit_price) AS min_price,
    MAX(oi.unit_price) AS max_price
FROM order_items oi
JOIN products p ON oi.product_id = p.product_id
JOIN categories cat ON p.category_id = cat.category_id
GROUP BY p.category_id, cat.category_name
ORDER BY total_revenue DESC;

Inside the snippet

At its core this is a single SELECT statement against order_items, products and categories.

The pieces that do the work: 2 JOINs combining rows across tables; COUNT, SUM, AVG, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Points of care

  • 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.

Using it

The order_items table is the working surface here.

FAQ

Which tables does the SQL touch?
`order_items`, `products`, `categories` — joined via 2 JOIN clauses.