The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate each group’s integer percentage of the total
SQL Server: Multiply before division and protect against a zero denominator.
SQL Server✓ Tested
Calculate each group’s numeric spread
SQL Server: Subtract MIN from MAX to report the difference between extremes.
SQL Server✓ Tested
Compute an integer weighted average
SQL Server: Multiply before summing and guard a zero total weight with NULLIF.
SQL Server✓ Tested
Count distinct values within a result
SQL Server: COUNT DISTINCT counts distinct non-null values.
SQL Server✓ Tested
Count rows satisfying separate conditions
SQL Server: SUM over CASE expressions calculates several conditional counts in one scan.
SQL Server✓ Tested
Distinguish row count from non-null value count
SQL Server: COUNT(*) includes every row while COUNT(column) skips NULL values.
SQL Server✓ Tested
Filter rows before grouping
SQL Server: WHERE limits the rows contributing to the aggregate; it differs from filtering completed groups with HAVING.
SQL Server✓ Tested
Group by more than one field
SQL Server: Each distinct combination of grouping fields produces its own row.
SQL Server✓ Tested
Return zero for a sum over no rows
SQL Server: SUM produces NULL for an empty input; COALESCE supplies the desired reporting default.
SQL Server✓ Tested
Turn known group values into columns
SQL Server: Conditional aggregation gives a portable pivot when the category set is known.
SQL Server✓ Tested