The readings table has one row per reading, with a reading_id and a numeric metric. For each row, compute z_score = (metric - mean) / stddev, where mean and stddev are the overall mean and the sample standard deviation of the metric column. Return one row per reading with reading_id, metric, z_score rounded to 4 decimals, and is_outlier, which is 1 when |z_score| > 1.96 and 0 otherwise.
Input Table(s)
readings
| Column | Type | Meaning |
|---|
| reading_id | INT | Identifier of the reading |
| metric | DECIMAL(10,2) | The measured value |
Primary key: reading_id.
Output Contract
Return these columns, in this order:
| Column | Meaning |
|---|
| reading_id | From the input |
| metric | From the input, unchanged |
| z_score | (metric - mean) / stddev, rounded to 4 decimal places |
| is_outlier | 1 when the absolute value of the unrounded z-score is greater than 1.96, else 0 |
Return one row for every row of readings, ordered by reading_id ascending.
Example
Example 1. Input readings:
| reading_id | metric |
|---|
| 267 | 65.99 |
| 693 | 71.26 |
| 737 | 71.05 |
| 302 | 22.67 |
| 892 | 28.78 |
| 298 | 63.85 |
| 410 | 71.28 |
| 741 | 53.16 |
Expected output:
| reading_id | metric | z_score | is_outlier |
|---|
| 267 | 65.99 | 0.5071 | 0 |
| 298 | 63.85 | 0.3984 | 0 |
| 302 | 22.67 | -1.6929 | 0 |
| 410 | 71.28 | 0.7757 | 0 |
| 693 | 71.26 | 0.7747 | 0 |
| 737 | 71.05 | 0.7641 | 0 |
| 741 | 53.16 | -0.1445 | 0 |
| 892 | 28.78 | -1.3826 | 0 |
The mean is 56.005 and the sample standard deviation is about 19.6910. The farthest row, 302, sits 1.6929 standard deviations below the mean, so nothing is flagged.
Example 2. Input readings:
| reading_id | metric |
|---|
| 101 | 10.00 |
| 102 | 10.00 |
| 103 | 10.00 |
| 104 | 10.00 |
| 105 | 10.00 |
| 106 | 40.00 |
Expected output:
| reading_id | metric | z_score | is_outlier |
|---|
| 101 | 10.00 | -0.4082 | 0 |
| 102 | 10.00 | -0.4082 | 0 |
| 103 | 10.00 | -0.4082 | 0 |
| 104 | 10.00 | -0.4082 | 0 |
| 105 | 10.00 | -0.4082 | 0 |
| 106 | 40.00 | 2.0412 | 1 |
The mean is 15 and the sample variance is 750 / 5 = 150, so the standard deviation is about 12.2474. Reading 106 is 25 above the mean, a z-score of about 2.0412, which is above 1.96.
Constraints and Clarifications
-
metric
is never NULL, and the table has at least two rows with different
metric
values, so the sample standard deviation is defined and positive.
-
Use the sample standard deviation, which divides the sum of squared deviations by
n−1
.
-
Decide
is_outlier
from the unrounded z-score. A z-score of exactly 1.96 or -1.96 is not an outlier.
-
Repeated
metric
values are allowed. Every input row appears once in the output.