Aggregation and pivots: SQL patterns and examples

Conditional counts, pivots, subtotals and weighted averages. The common failure is aggregating at the wrong grain, so check what one row of your table represents first.