// aggregates reference

SQL COVAR_SAMP function

Sample covariance of two columns: divides by n-1 over the complete pairs.

类别
Aggregates
Returns
numeric
In this category
26 of 52

语法

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

引擎支持

引擎Support备注
SQL Server Not built in same manual route; cast integers to float
PostgreSQL 是 Supported under this name.
MySQL Not built in compute manually: (SUM(y*x) - SUM(y)*SUM(x)/COUNT(*)) / (COUNT(*) - 1) over complete pairs
SQLite Not built in No built-in equivalent.
Oracle 是 Supported under this name.

示例

PostgreSQL

SELECT covar_samp(height, weight) FROM people;

Oracle

SELECT COVAR_SAMP(salary, age) FROM employees;

值得了解

  • Rows where either input is NULL are dropped; covariance runs on complete pairs only.
  • One complete pair returns NULL: the n-1 divisor needs at least two pairs.
  • Read the sign, not the size: covariance is in y-units times x-units, so its magnitude changes when you rescale a column. CORR divides that scale out.

Questions about COVAR_SAMP

COVAR_SAMP vs COVAR_POP?

The divisor: n-1 versus n; a single pair gives NULL versus 0.

Which engines have it?

PostgreSQL and Oracle. MySQL and SQL Server need the manual formula (SUM(y*x) - SUM(y)*SUM(x)/COUNT(*)) / (COUNT(*) - 1), run over complete pairs only.

How is covariance used in CORR?

CORR is COVAR_POP divided by the product of the two population standard deviations.

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.