A company wants to evaluate user engagement by signup cohort. Write a PostgreSQL query that summarizes qualifying transactions by user and calendar month, calculates each user's cumulative spend, and ranks users within their signup cohort.
Requirements
- Derive
cohort_month from users.signup_date and activity_month from transactions.transaction_date.
- Include only transactions on or after the user's signup date. Exclude transactions that cannot be matched to a user.
- Aggregate transaction amounts by user and activity month.
- Calculate a per-user running total ordered by activity month, and rank users within each cohort by total spend descending. Preserve ties with the same rank.
- Return one row per user and activity month, ordered by cohort, activity month, and user ID.
Output details
- Return columns in this order:
user_id, user_name, cohort_month, activity_month, monthly_spend, user_total_spend, running_total, cohort_rank.
- Order rows by
cohort_month ascending, activity_month ascending, then user_id ascending.
- Rank users by
user_total_spend descending, place NULL totals last, and assign identical ranks to ties.
- Preserve
NULL aggregate amounts as NULL; do not convert them to 0.