// aggregates reference

SQL REGR_SLOPE function

Returns the slope of the least-squares line fitted to the complete (y, x) pairs of a group.

類別
Aggregates
Returns
numeric
In this category
28 of 52

語法

REGR_SLOPE(y, x) | REGR_SLOPE(y, x) OVER (...)

引擎支援

引擎Support備註
SQL Server Not built in same manual formula; cast integers to float
PostgreSQL 是 Supported under this name.
MySQL Not built in manual: (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs
SQLite Not built in No built-in equivalent.
Oracle 是 Supported under this name.

範例

PostgreSQL

SELECT regr_slope(sales, ad_spend) FROM monthly;

Oracle

SELECT REGR_SLOPE(sales, ad_spend) OVER (PARTITION BY region) FROM monthly;

小知識

  • Only complete pairs count: a NULL in y or x drops the row.
  • The result is NULL when there are fewer than two pairs or when every x is the same (VAR_POP(x) = 0).
  • The companion intercept is REGR_INTERCEPT(y, x) = AVG(y) - REGR_SLOPE(y, x) * AVG(x).
  • MySQL and SQL Server have no REGR_ functions; slope = (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)).

Questions about REGR_SLOPE

What is REGR_SLOPE mathematically?

COVAR_POP(y, x) / VAR_POP(x), the least-squares estimate of dy/dx.

Why is my result NULL?

Fewer than two complete pairs, or every x value identical, leaves the slope undefined.

Does MySQL have REGR_SLOPE?

No; compute (AVG(y*x) - AVG(y)*AVG(x)) / (AVG(x*x) - AVG(x)*AVG(x)) over complete pairs.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.