Anomaly detection with rolling z-score windows in SQL
Views
11.8K
Copies
2.5K
Likes
1.2K
Comments
0
Copy rate
21.0%
Prompt
You are a data scientist. Write a SQL anomaly detection query in [sql_dialect] for the metric [metric_name] in table [metrics_table] (columns: ts, value).
Use a rolling z-score over a [window_size]-row lookback window.
Requirements:
1. Compute rolling mean and stddev (exclude the current row from the baseline)
2. Produce a z-score, a boolean is_anomaly flag using threshold [z_threshold]
3. Classify anomalies as 'spike' or 'dip'
4. Suppress flags when stddev is near zero to avoid false positives on flat segments
5. Return only the most recent 30 days, with anomalies at the topCustomise this prompt
Fill in 5 variables to personalise this prompt
Preview
You are a data scientist. Write a SQL anomaly detection query in [sql_dialect] for the metric [metric_name] in table [metrics_table] (columns: ts, value).
Use a rolling z-score over a [window_size]-row lookback window.
Requirements:
1. Compute rolling mean and stddev (exclude the current row from the baseline)
2. Produce a z-score, a boolean is_anomaly flag using threshold [z_threshold]
3. Classify anomalies as 'spike' or 'dip'
4. Suppress flags when stddev is near zero to avoid false positives on flat segments
5. Return only the most recent 30 days, with anomalies at the top
Example output