Timedora

Analytical SQL: CTEs and Window Functions

A practical guide to structuring analytical SQL with CTEs and applying window functions to rankings, rolling metrics, and cohort retention.

Structure Queries and Rank Results

Name each stage and verify its

A gives an intermediate query a name so later stages can refer to it. In PostgreSQL, introduce one with WITH, then provide a name and a parenthesized query. A CTE exists only for the statement that defines it; it is not a permanent table.

A useful structure names stages by purpose: filter or clean the source, aggregate to the needed for analysis, calculate analytical measures, and then select the output. For example, the source query first defines clean_events, filtering out rows without a user_id. Its next stage, daily_users, groups those events by event_time::date and counts distinct users. The final query selects and orders the daily results.

The changes between those stages: clean_events has one row per source event, while daily_users has one row per day. Make that change explicit in your reasoning. If you join stages with incompatible grains, a row may match multiple rows and inflate counts or sums. CTEs make the stages easier to inspect, but they are organizational tools—not necessarily stored intermediate tables or performance optimizations. The database may transform them during planning.

Use windows for row-level comparisons

A uses OVER to specify which rows contribute to a calculation. PARTITION BY starts a separate calculation for each group; ORDER BY defines the sequence or ranking within that group. Unlike an ordinary aggregation, a returns a value for each input row, so the rows and their other columns remain available.

Choose the function to match the question:

  • ROW_NUMBER() gives each row a unique position within its partition.

  • RANK() assigns equal values the same rank and leaves gaps after ties. If two rows tie at rank 1, the next rank is 3.

  • DENSE_RANK() also gives ties the same rank, but has no gaps; after a tie at rank 1, the next rank is 2.

  • An aggregate such as SUM() can also be used with OVER to calculate cumulative or rolling measures.

Rank monthly product revenue

The monthly sales example first groups transactions to one row per month and product, summing net_amount as revenue. Only then does it apply a ranking window, partitioned by month and ordered by revenue descending. This order matters: ranking the raw transactions would rank transaction rows, not monthly product totals.

The query uses RANK() <= 3 to keep the top three rank positions in each month. That does not guarantee exactly three products: if multiple products tie at a qualifying rank, all are kept. When the requirement is exactly three rows per month, use ROW_NUMBER() instead and add a deterministic tie-breaker, such as ordering by descending revenue and then product_id. The tie-breaker makes the choice among equal revenues consistent.

These examples use PostgreSQL syntax. CTE behavior and date-related syntax can differ across SQL systems.

Build Calendar-Day Rolling Metrics

Make the rows correspond to days

A frame written as ROWS BETWEEN 6 PRECEDING AND CURRENT ROW includes the current row and the six rows before it. It therefore covers seven rows, not necessarily seven calendar days. If the input omits dates with no transactions, seven consecutive rows could span more than a week.

To calculate a calendar-day rolling total, first make the data daily and complete:

  1. Aggregate transactions to one revenue total per date.

  2. Generate a covering the reporting period and the six earlier days needed for the first reported window. PostgreSQL's generate_series can produce this sequence.

  3. Left join the daily totals to the spine and use COALESCE to replace missing revenue with zero. The result has one row for every calendar day.

  4. Apply SUM(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) to that complete series.

The source example reports from April 1, 2025, up to but not including May 1. Its begins six days before the report start and ends on the day before the report end. That lookback ensures April 1's rolling window includes March 26 through April 1: seven calendar days. The final selection filters the rolling results to the reporting range, leaving the lookback dates available to calculate the first reported value without displaying them.

The half-open range—start included, end excluded—also makes the boundary explicit. For timestamp data, choose the intended business time zone before converting timestamps to dates: timestamp-to-date conversion and date truncation can depend on time-zone settings. This date-spine pattern and its date functions are shown with PostgreSQL syntax; other SQL systems may differ.

Construct a - Table

Define the , period, and denominator

A monthly groups users by the month of their first recorded event. For a and month number n, is the number of users with at least one event in that month divided by the size. Month 0 is the month. The denominator stays the original size; it does not shrink to the number active in the preceding month.

The source example reports months 0 through 6 and sets as_of_month to July 1, 2025. Its event filter includes records before that date, and the -period grid excludes any activity month that is not earlier than the cutoff. Because the cutoff is the first day of a month, the example includes only complete months.

Build the query in stages

The example uses CTEs to make each part of the calculation visible:

  1. Select events and derive activity month. Exclude null user IDs and convert event times to their calendar month. This defines which recorded activity can establish a or count as .

  2. Assign cohorts. Group by user and take the minimum activity month. Each user then has one month.

  3. Count sizes. Group those user-to- assignments by month. This count supplies the denominator.

  4. Deduplicate monthly activity. Select distinct user-and-month pairs. A user with several events in a month can then be counted only once for that period.

  5. Create periods and a -period grid. Generate month numbers 0 through 6, combine them with each , and keep only periods before the cutoff. This creates a row even when a has no returning users in a period.

  6. Left join activity and calculate . Match each grid row to the users in that and their activity in the corresponding month. Count matched user IDs for retained users, then divide by size. The example uses NULLIF(cohort_size, 0) to guard against division by zero and rounds the percentage to one decimal place.

The grid is essential for showing a zero rather than omitting a -period with no activity: the left join preserves the grid row, and its unmatched activity contributes no user ID to the count. Deduplicating activity first makes that count a count of users, not events.

Finally, verify that the events represent the activity your definition intends to measure. assignment and later activity must use consistent user identity and time-zone rules. The example's monthly truncation and cutoff use PostgreSQL syntax; confirm equivalent date behavior in another SQL system.

  • : The ordered set of rows included in a window calculation.