How would you use SQL window functions to calculate a 7-day rolling average and rank users within each cohort?
Write a PostgreSQL query using the provided user and activity data. Calculate each active user's rolling average through their latest activity date, then rank users within the same cohort. Users without activity should be excluded.
user_id, cohort_date, latest_activity_date, rolling_7_day_average, and cohort_rank.cohort_date, cohort_rank, and user_id.NULL activity values as ignored by averaging, but return NULL when no non-NULL value exists; preserve zero values as zero.rolling_7_day_average; do not round or cast it.NULL values according to PostgreSQL's default descending sort behavior.| Column | Type | Description |
|---|---|---|
| user_idPK | INT | Unique user identifier |
| user_name | VARCHAR(100) | User display name |
| cohort_date | DATE | Date the user entered the cohort |
| Column | Type | Description |
|---|---|---|
| activity_idPK | INT | Unique activity record identifier |
| user_id | INT | User associated with the activity |
| activity_date | DATE | Calendar date of activity |
| activity_count | INT | Number of activities recorded that day |