liveBook · Manning

Data aggregation

As explained in Learn SQL in a Month of Lunches

Aggregation is the SQL operation of combining or summarizing data values to produce grouped or otherwise consolidated results.

Data aggregation combines or summarizes values so a query can analyze groups rather than only individual rows. GROUP BY divides one result set into logical groups, such as orders grouped by promotion code. section 12.2

Count orders by promotion code

To find promotion codes used in orders, join orderheader to promotion, group by PromotionCode, and count PromotionID. Add HAVING COUNT(oh.PromotionID) >= 3 to keep only codes used at least three times. WHERE filters individual rows; HAVING filters aggregated groups. section 12.3

Practical details to remember:

  • GROUP BY includes NULL as a group, unlike COUNT applied without grouping, which excludes NULL values from the counted column. section 12.2.2
  • Logical processing evaluates FROM, WHERE, SELECT, GROUP BY, HAVING, and ORDER BY in sequence; avoid relying on column aliases in HAVING because database products can differ. section 12.4
SELECT
    p.PromotionCode,
    COUNT(oh.PromotionID) AS OrdersWithPromotionCode
FROM orderheader oh
INNER JOIN promotion p
    ON oh.PromotionID = p.PromotionID
GROUP BY p.PromotionCode
HAVING COUNT(oh.PromotionID) >= 3
ORDER BY p.PromotionCode;

Inspect a complete grouped query that joins promotion data, counts matching orders, and filters groups with HAVING. section 12.3

How Learn SQL in a Month of Lunches covers it

How deep it goes
Explains GROUP BY, NULL handling, HAVING, joins, counts, clause order, and alias portability through practical queries.
Examples
Demonstrates order counts by PromotionID, promotion-code counts, NULL groups, INNER JOIN results, and a three-use HAVING threshold.
What it assumes
Assumes familiarity with SELECT, joins, filtering, aliases, and COUNT while explaining grouped analysis through practical examples.
What you can do after
Builds grouped SQL queries that count records, preserve NULL groups, and filter aggregated results with HAVING.
How it connects
Connects GROUP BY with aggregate functions, NULL values, WHERE, HAVING, INNER JOIN, ORDER BY, and column aliases.

Also explained in

Compare how 19 books explain data aggregation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn SQL in a Month of Lunches. The section links point to the parts of the book it draws on.