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.

SqlData Integrity

Code

snippet
-- 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 WHERE and GROUP BY — their output is not visible to a same-level WHERE.

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

FAQ

Which tables does the SQL touch?
`region_daily` — referenced directly, no join needed.