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.

SqlData Fetching

Code

snippet
-- 用最小二乘回归在 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

FAQ

What objects does the SQL involve?
`monthly_revenue`, `fit` — joined via one JOIN clause.