CORR Pearson Correlation Coefficient
CORR measures the Pearson correlation of two columns per group, also works as a window aggregate, and returns NULL when a variance is zero.
Code
-- CORR(y, x):Pearson 相关系数,取值 -1..1;方差为 0 时返回 NULL
SELECT
region,
CORR(spend_cents, orders_count) AS correlation,
COVAR_SAMP(spend_cents, orders_count) AS covar_sample,
COUNT(*) AS observations
FROM region_daily
GROUP BY region
HAVING COUNT(*) > 1;
-- 同一系数当窗口函数:按时间滚动观察两个指标关系的稳定性
SELECT
day,
CORR(spend_cents, orders_count) OVER (
ORDER BY day
RANGE BETWEEN INTERVAL '30 days' PRECEDING
AND CURRENT ROW
) AS rolling_correlation
FROM region_daily
WHERE region = 'apac';How the snippet works
The file runs SELECT statements, touching region_daily.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) evaluating each row against its frame while every row stays in the output; an ORDER BY that fixes the output order.
What to watch for
- Window functions are evaluated after
WHEREandGROUP BY— their output is not visible to a same-levelWHERE.
Applying it
Run it in the region_daily database context.
Statements that matter
SELECT
day,
CORR(spend_cents, orders_count) OVER (
ORDER BY day
RANGE BETWEEN INTERVAL '30 days' PRECEDING
AND CURRENT ROW
) AS rolling_correlation
FROM region_daily
WHERE region = 'apac';
SELECT
region,
CORR(spend_cents, orders_count) AS correlation,
COVAR_SAMP(spend_cents, orders_count) AS covar_sample,
COUNT(*) AS observations
FROM region_daily
GROUP BY region
HAVING COUNT(*) > 1;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does the SQL touch?
- `region_daily` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.