Calculating a Rate in SQL

A rate computation should select a suitable denominator, handle empty groups, and use arithmetic supporting the requested precision.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace three observations
  2. Expose counts if useful
  3. Make the numerator, denominator and division type visible
  4. Preserve the counts needed to recompute summaries

Trace three observations

One success in three observations yields \(1/3\). Integer division can truncate in some expressions. Convert to an appropriate numeric type using dialect rules. Integer and fractional quotients explain the underlying distinction.

Expose counts if useful

A null rate for zero observations can be more informative than zero successes out of several. Include count fields to communicate that difference. See combining group rates.[1]

Make the numerator, denominator and division type visible

If three of eight records qualify, a numeric rate is 0.375. Integer division in some databases can truncate this to zero for integer operands. Decide what an empty denominator means and handle it explicitly. See combining unequal group rates.

WITH stats(successes, observations) AS (VALUES (3,8), (0,0))
SELECT successes * 1.0/NULLIF(observations,0) AS rate FROM stats ORDER BY observations DESC;
-- Expected: 0.375, null.

Preserve the counts needed to recompute summaries

Rounding a percentage for display should not replace its underlying counts. Test no observations, zero successes with observations, and a noninteger result.

References

  1. PostgreSQL Global Development Group, Queries ↩