regr_slope And regr_intercept Trend
Fit a trend line inside one aggregate pass: regr_slope and regr_intercept return the least squares line, and regr_r2 reports how linear the relationship is.
Code
-- 用最小二乘回归在 SQL 里拟合趋势线(trend line):斜率与截距一次聚合算出
-- regr_slope(y, x) = Σ(x-x̄)(y-ȳ) / Σ(x-x̄)²;regr_intercept = ȳ - slope·x̄
-- 任一侧为 NULL 的行会被成对剔除,不参与拟合
SELECT
regr_slope(revenue, month_index) AS monthly_slope,
regr_intercept(revenue, month_index) AS baseline
FROM monthly_revenue;
-- 拟合质量:regr_r2 接近 1 说明线性关系强,接近 0 说明几乎无线性关系
SELECT regr_r2(revenue, month_index) AS r_squared
FROM monthly_revenue;
-- 把拟合线与实际值并排输出,快速核对偏差
WITH fit AS (
SELECT regr_slope(revenue, month_index) AS slope,
regr_intercept(revenue, month_index) AS intercept
FROM monthly_revenue
)
SELECT m.month_index, m.revenue,
f.intercept + f.slope * m.month_index AS fitted
FROM monthly_revenue m
CROSS JOIN fit
ORDER BY m.month_index;How it works
Several statements share this file — SELECT, with monthly_revenue and fit among the objects involved.
What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; an ORDER BY that fixes the output order.
Putting it to use
The monthly_revenue table is the working surface here.
Core lines
WITH fit AS (
SELECT regr_slope(revenue, month_index) AS slope,
regr_intercept(revenue, month_index) AS intercept
FROM monthly_revenue
)
SELECT m.month_index, m.revenue,
f.intercept + f.slope * m.month_index AS fitted
FROM monthly_revenue m
CROSS JOIN fit
ORDER BY m.month_index;
SELECT
regr_slope(revenue, month_index) AS monthly_slope,
regr_intercept(revenue, month_index) AS baseline
FROM monthly_revenue;
SELECT regr_r2(revenue, month_index) AS r_squared
FROM monthly_revenue;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `monthly_revenue`, `fit` — joined via one JOIN clause.
Report a problem with this exampleOpens a pre-filled issue on GitHub.