Compute the least-squares slope and intercept of y on x in SQL
Quick Overview
Write a SQL query that fits an ordinary least-squares line of y on x from a table of paired observations and returns the slope and intercept rounded to four decimals. It tests building regression estimates from aggregate sums, numeric precision and the order of rounding.
Compute the least-squares slope and intercept of y on x in SQL
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
The `paired` table holds paired observations `x` and `y`. Fit the least-squares line of `y` on `x` and return one row with `slope` and `intercept`, each rounded to 4 decimals.
Use the raw-sum formulas, where $n$ is the row count and $S_x$, $S_y$, $S_{xy}$, $S_{xx}$ are the sums of $x$, $y$, $xy$ and $x^2$ over all rows:
$$
\text{slope} = \frac{n S_{xy} - S_x S_y}{n S_{xx} - S_x^2}
\qquad
\text{intercept} = \frac{S_y - \text{slope} \cdot S_x}{n}
$$
```hint Where the inputs come from
Every quantity in both formulas is either the row count or a sum over the rows.
```
### Input Table(s)
`paired`
| Column | Type | Meaning |
|---|---|---|
| x | DECIMAL(10,4) | Predictor value |
| y | DECIMAL(10,4) | Response value |
No primary key. Two rows with the same `x` and `y` are two separate observations.
### Output Contract
Return exactly one row with these columns, in this order:
| Column | Meaning |
|---|---|
| slope | The least-squares slope, rounded to 4 decimal places |
| intercept | The least-squares intercept, rounded to 4 decimal places |
Compute the intercept from the unrounded slope and round only the final values. The result is a single row, so no ordering is needed.
### Example
`paired`
| x | y |
|---|---|
| 19.9 | 18.6 |
| 37.9 | 54.1 |
| 39.8 | 52.5 |
| 45.5 | 46.9 |
| 46.2 | 55.8 |
| 47.1 | 43.9 |
| 49.7 | 49.4 |
| 47.9 | 54.1 |
| 30.9 | 34.3 |
| 11.2 | 22.6 |
Expected output:
| slope | intercept |
|---|---|
| 0.9058 | 9.1541 |
With $n = 10$ the formulas give a slope of about 0.905768 and an intercept of about 9.154069 before rounding.
### Constraints and Clarifications
- `x` and `y` are never NULL.
- The table has at least two rows with different `x` values, so the slope's denominator is not zero.
- Duplicate rows all count toward $n$ and the sums.
- Rounding the slope before computing the intercept changes the answer: on the example it gives 9.1529 instead of 9.1541.
Overview: Write a SQL query that fits an ordinary least-squares line of y on x from a table of paired observations and returns the slope and intercept rounded to four decimals. It tests building regression estimates from aggregate sums, numeric precision and the order of rounding.
The paired table holds paired observations x and y. Fit the least-squares line of y on x and return one row with slope and intercept, each rounded to 4 decimals.
Use the raw-sum formulas, where n is the row count and Sx, Sy, Sxy, Sxx are the sums of x, y, xy and x2 over all rows: