CORR Trend Per Partition Window

Layer a CTE and window functions: CORR measures ad-spend to revenue correlation inside each region partition instead of one pooled number.

SqlData Integrity

Code

snippet
WITH spend AS (
    SELECT
        region,
        week,
        ad_spend,
        revenue
    FROM weekly_metrics
),
scored AS (
    SELECT
        region,
        week,
        ad_spend,
        revenue,
        -- 相关性按 region 分区计算:同一窗口里混入其他区域会稀释结论
        round(CORR(ad_spend, revenue)
              OVER (PARTITION BY region)::numeric, 3) AS spend_revenue_corr,
        round(REGR_COUNT(ad_spend, revenue)
              OVER (PARTITION BY region)::numeric) AS n_obs
    FROM spend
)
SELECT
    region,
    min(week) AS first_week,
    max(week) AS last_week,
    n_obs,
    spend_revenue_corr,
    CASE
        WHEN spend_revenue_corr >= 0.7 THEN 'strong positive'
        WHEN spend_revenue_corr >= 0.3 THEN 'weak positive'
        ELSE 'no reliable signal'
    END AS verdict
FROM scored
GROUP BY region, n_obs, spend_revenue_corr
ORDER BY spend_revenue_corr DESC;

How the snippet works

At its core this is a single SELECT statement against weekly_metrics, spend and scored.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Points of care

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

Run the statement against the weekly_metrics table.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`weekly_metrics`, `spend`, `scored`.