0%

Summarize Many Rows · practice

Filter Finished Groups with HAVING

After the fourteen-day row filter, electronics has only one contributing item. Suppose the report should show categories only when at least two qualifying items support the summary. That rule cannot be decided by looking at one source row; it depends on the completed group count.

Open summary.sql. Add this line between GROUP BY category and ORDER BY category ASC:

HAVING COUNT(*) >= 2

Press Run. The electronics group disappears, while events and tools remain:

Columns: category | item_count | total_loan_days | shortest_loan_days | longest_loan_days | average_loan_days
events | 2 | 21 | 7 | 14 | 10.5
tools | 2 | 10 | 3 | 7 | 5.0

The query now makes two different filtering decisions at two different stages. WHERE loan_days <= 14 examines individual items before groups form. HAVING COUNT(*) >= 2 examines each completed category group after SQLite knows how many qualifying rows it contains.

The visible groups reach HAVING with these counts:

Completed groupQualifying row countKept?
electronics1no
events2yes
tools2yes

The group filter reads those completed counts; it does not revisit individual item periods.

This distinction matters for electronics. The table starts with two electronics items, but the speaker fails the WHERE rule. The completed electronics group therefore has a count of one, and HAVING removes it. Counting before the row filter would answer a different question.

The boundary is inclusive again. A group with exactly two qualifying items should stay, so the comparison is >= 2, not > 2.

Keep the maximum-period rule in WHERE. Moving it into HAVING would stop it from removing individual source rows before the totals and averages are calculated. Keep the minimum-group-size rule in HAVING because a source row does not carry its group’s final count.

You may notice COUNT(*) in both the selected result and the HAVING . They refer to the same completed group count. One displays it for the reader; the other uses it to decide whether that group belongs in the answer.

Submit includes one group with a single qualifying row, one with exactly two, and one that begins with two rows but falls to one after the row filter. If the last group remains, check which stage produced the count used by HAVING.

You can now read the query as a sequence of questions: Which items may contribute? How are they grouped? Which completed groups are large enough to report? Each clause has one clear decision to make.

Task

Add HAVING COUNT(*) >= 2 between GROUP BY category and ORDER BY category ASC in summary.sql.

Keep the source-row rule in WHERE, run the query, and submit the remaining groups.