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.
Code
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-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Run the statement against the weekly_metrics table.
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `weekly_metrics`, `spend`, `scored`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.