How would you compute a linear regression slope and intercept or a weighted average directly in SQL using aggregate functions?
Last updated
Weighted average is
SUM(x * w) / NULLIF(SUM(w), 0), which guards against division by zero.Least-squares regression uses one-pass sums. Slope = (n·Σxy − Σx·Σy) / (n·Σx² − (Σx)²) and intercept = (Σy − slope·Σx) / n.
Prefer built-ins where available:
REGR_SLOPE(y, x),REGR_INTERCEPT(y, x),REGR_R2(y comes first). AddGROUP BYto fit a line per segment.
- https://duckdb.org/docs/preview/sql/functions/aggregates
- https://www.certsafari.com/snowflake/snowpro-advanced-data-scientist/learn/approximate-functions-and-linear-regression-in-snowflake-sql
- https://www.hisqlboy.com/blog/calculating-weighted-averages-sql
- https://www.tigerdata.com/learn/time-series-forecasting