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.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL, Oracle.
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.