Given a table paired of numeric observations x and y, compute the sample covariance with the raw-sum formula
cov=n(n−1)n⋅Sxy−Sx⋅Sy
where n is the row count, Sxy=∑xy, Sx=∑x and Sy=∑y. Return one row with covariance rounded to 4 decimals.
Input Table(s)
Table paired
| Column | Type | Meaning |
|---|
| x | DECIMAL(10,4) | First value of the pair |
| y | DECIMAL(10,4) | Second value of the pair |
The table has no primary key. Each row is one paired observation, and identical rows count as separate observations.
Output Contract
-
Exactly one row with one column,
covariance
.
-
covariance
is the value of the formula above, rounded to 4 decimal places.
-
The result always has a single row, so no ordering applies.
Example
Input paired:
| x | y |
|---|
| 7.8 | 23.3 |
| 26.8 | 27.5 |
| 45.6 | 53.1 |
| 16.7 | 29 |
| 19.2 | 32.3 |
| 31 | 42.9 |
| 42 | 65.1 |
| 5.7 | 20.2 |
| 43.5 | 56.9 |
Expected output:
Here n=9, Sx=238.3, Sy=350.3 and Sxy=11098.95, so the numerator is 9⋅11098.95−238.3⋅350.3=16414.06 and the denominator is 9⋅8=72. The ratio is 227.973055..., which rounds to 227.9731.
Constraints and Clarifications
-
Neither
x
nor
y
is NULL.
-
Every row counts once in
n
and in each sum, including repeated rows.
-
With fewer than two rows the sample covariance is undefined. Return one row with
covariance
set to NULL; the query must not fail with a division-by-zero error.
-
Compute the value from the raw-sum formula as written. A built-in such as
COVAR_SAMP
gives the same number after rounding, but the exercise is to build it from
COUNT
and
SUM
.