How do you optimize query performance on a database containing billions of rows of historical data?
Use the provided PostgreSQL schema to produce an efficient report for completed events during 2025. The result should aggregate monthly activity for active accounts and calculate each account and event type's change from the previous month.
Output
- One row per active account, event type, and month with qualifying activity.
- Columns:
account_name, region, event_name, month_start, event_count, total_amount, prior_month_amount, and amount_change.
- Sort by account, event type, and month in ascending order.
Output details
- Treat 2025 as the half-open interval from
2025-01-01 inclusive through 2026-01-01 exclusive.
- Sort ascending by
account_id, then event_type_id, then month_start, not by the displayed names.
- Preserve NULL
region values.
- Leave
prior_month_amount NULL for each account and event type's first observed month.
- Treat a missing prior amount as numeric zero when calculating
amount_change.
- Treat an all-NULL monthly amount sum as numeric zero without rounding.