# Unit 4 — Aggregate at the grain of the question

**Outcome U4:** construct grouped summaries, reconcile them to source controls and choose defensible denominators, including empty populations. **Suggested work:** five hours; unpiloted.

## 1. Aggregation changes what a row means

Before grouping, a registration row describes a booking. After `GROUP BY session_id`, each result row describes a session **represented among the selected bookings**. A group can contain several booking rows. You must now decide which values can be combined and what each aggregate means.

```sql
SELECT session_id,COUNT(*) AS booking_rows,SUM(seats) AS booked_seats,
       COUNT(attended) AS recorded_attendance_rows,
       SUM(attended) AS recorded_attended_seats
FROM registrations GROUP BY session_id ORDER BY session_id;
```

The base result is:

| Session | Booking rows | Booked seats | Rows with attendance | Recorded attended seats |
|---:|---:|---:|---:|---:|
|101|3|4|2|2|
|102|2|4|2|3|
|103|2|3|1|1|
|105|3|3|3|2|

There is no group for 104 or 106 because no registration row supplies those session IDs. Their absence is not a zero-valued row. Unit 6 will start with sessions and join preaggregated bookings to show every session.

The totals reconcile: booking rows 3+2+2+3=10; seats 4+4+3+3=14; known attendance rows 2+2+1+3=8; recorded attendance 2+3+1+2=8. Reconciliation catches a missing or duplicated group, but it does not by itself establish correct definitions.

## 2. Choose grouping fields, not accidental values

Select only group keys and aggregates in a portable, interpretable grouped query. SQLite permits some bare non-grouped columns, but their value may come from an arbitrary contributing row. A query selecting `session_id,booking_ref,SUM(seats)` while grouping only by session does not tell you which booking reference meaningfully represents the group. It invites a plausible-looking but unsupported label.

A common safe pattern is to aggregate bookings by session ID first, then join the resulting one-row-per-session table to session attributes. Another is to group by all requested stable dimensions. In either case state the result grain explicitly.

`COUNT(*)` and `SUM(seats)` answer different questions even when they occasionally match. One two-seat booking contributes one to the first and two to the second. Do not choose whichever measure produces the expected-looking number.

## 3. WHERE selects rows; HAVING selects groups

`WHERE seats>=2` removes small bookings **before** a grouped sum. `HAVING SUM(seats)>=4` keeps session groups whose total booked seats are at least four **after** aggregation. In base the latter retains sessions 101 and 102, each with four seats. They arrive at four through different booking counts.

To test the difference, compare a session with two one-seat bookings and a session with one two-seat booking. Both total two seats; filtering rows for `seats>=2` keeps only the latter. A grouping question is not always solved by a row filter.

An SQL engine can rearrange work internally, so “before” and “after” here describe the logical result, not an instruction to measure physical execution speed.

## 4. An average is a numerator-denominator pair

The overall mean booking size is 14/10 = **1.4 seats per booking**. It is not attendance and not a mean number of people per session. The mean of the four session booked-seat totals is 14/4 = 3.5, but that excludes the two sessions with no bookings. Over all six listed sessions it would be 14/6 ≈ 2.3333. Over only the five open sessions it would be 14/5 = 2.8. Each has a different population.

For known attendance, first restrict to bookings whose attendance is recorded, then compute attended seats divided by booked seats **within that same subset**:

```sql
SELECT session_id,SUM(attended) AS attended_seats,
       SUM(seats) AS known_booked_seats,
       ROUND(100.0*SUM(attended)/NULLIF(SUM(seats),0),2) AS known_attendance_pct
FROM registrations WHERE attended IS NOT NULL
GROUP BY session_id ORDER BY session_id;
```

The base session percentages are 66.67%,75%,100%,66.67%, with known-seat denominators 3,4,1,3. Their simple average is not the overall known-seat attendance percentage. The correct pooled ratio is (2+3+1+2)/(3+4+1+3) = 8/11 ≈ **72.73%**. Weighting by the denominators would give the same pooled result; averaging rounded percentages introduces extra error.

This known-only ratio describes recorded cases, not all booked seats unless missingness assumptions are justified. Session 103's 100% is especially fragile: only one of its three booked seats has recorded attendance. A smaller denominator can make an impressive rate less informative.

## 5. Empty and zero are different again

Run `u04_empty_summary`, which selects `seats>100`. No supplied booking meets that condition. A scalar aggregate still returns one row: COUNT 0, SUM NULL, AVG NULL. With GROUP BY and no selected rows, there are no groups, so no result rows.

`NULLIF(denominator,0)` converts a zero denominator to NULL. It makes a rate explicitly unavailable instead of pretending no observations is 0% performance. Our later reporting convention may display additive totals as zero for an empty set, but a mean or rate remains unavailable. State the convention alongside the output.

## Practice and checkpoint

Complete **G4** and **I4**. Independently sum group outputs to source totals before viewing the key. For the October fixture, known booked seats are a different denominator from all booked seats; do not inherit September's fraction by memory.

Checkpoint **C4**: explain why the average of session attendance percentages can differ from the percentage obtained by pooling counts. Then show what your query returns for an empty fixture. Save `group-summary.sql`, its results and a `denominators.md` note. These are the prerequisites for the retained JOIN unit; if you cannot explain row counts versus entity counts, return to Units 1 and 3 before proceeding.
