Uncategorized

SQL Window Functions: Rankings and Seven-Day Rolling Totals

Quick answer

Use a window function with OVER (...) to calculate rankings or totals while keeping individual rows. Use PARTITION BY to separate stores or other groups. For daily data, RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW covers the current date and six preceding calendar dates. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW covers seven records—not necessarily seven days. (postgresql.org)

The examples below use PostgreSQL 18 syntax and synthetic sales data. You need a PostgreSQL connection and basic familiarity with SELECT, ORDER BY, and SUM. Run the examples in order, in the same database session.

1. Start with a clear question and one row per store-day

Suppose you want to answer two questions:

  • Which recorded dates had the highest sales within each store?
  • What were total sales over each date and the preceding six calendar dates?

First, define the grain: what one row represents. Here, it is one store on one date. Do not apply a seven-row calculation directly to transaction-level data and describe the result as seven days.

Create this practice table:

CREATE TEMP TABLE daily_sales (
    store text NOT NULL,
    sale_date date NOT NULL,
    sales numeric(12, 2),
    PRIMARY KEY (store, sale_date)
);

INSERT INTO daily_sales (store, sale_date, sales)
VALUES
    ('A', DATE '2026-01-01', 10),
    ('A', DATE '2026-01-02', 20),
    ('A', DATE '2026-01-03', 20),
    ('A', DATE '2026-01-05', 40),
    ('A', DATE '2026-01-06', 50),
    ('A', DATE '2026-01-07', 60),
    ('A', DATE '2026-01-08', 70),
    ('A', DATE '2026-01-09', 80);

These are invented teaching values, not business results. For this exercise, January 4 is a confirmed zero-sales day omitted from the input. There are no unknown sales amounts among the inserted rows.

The primary key prevents duplicate store-date combinations. The sales column remains nullable so we can discuss unknown amounts later. PostgreSQL primary keys enforce uniqueness and non-null key values. (postgresql.org)

For real data, also define what “sales” includes: refunds, tax, canceled orders, and currency conversions can change the meaning of the metric. If your source contains transactions, summarize them to the required daily grain first.

2. Understand the three parts of a window

A window calculation has three important controls:

SUM(sales) OVER (
    PARTITION BY store
    ORDER BY sale_date
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
)
  • PARTITION BY store creates a separate calculation group for each store.
  • ORDER BY sale_date determines the sequence inside that group.
  • The frame selects the rows included in the calculation for the current row. (postgresql.org)

Unlike a grouped aggregate, a window function does not collapse its input rows into one row per group. You can display the date, its sales, and a calculated total together. (postgresql.org)

Without PARTITION BY, every input row belongs to one partition. That is appropriate for a company-wide calculation, but not for separate store totals. (postgresql.org)

The ordering inside OVER is for the calculation. Use a final query-level ORDER BY when you also want predictable display order. (postgresql.org)

3. Choose a ranking function that handles ties correctly

Use this query to compare three ranking choices:

SELECT
    store,
    sale_date,
    sales,
    ROW_NUMBER() OVER (
        PARTITION BY store
        ORDER BY sales DESC NULLS LAST, sale_date
    ) AS row_position,
    RANK() OVER (
        PARTITION BY store
        ORDER BY sales DESC NULLS LAST
    ) AS sales_rank,
    DENSE_RANK() OVER (
        PARTITION BY store
        ORDER BY sales DESC NULLS LAST
    ) AS dense_sales_rank
FROM daily_sales
ORDER BY store, row_position;

The ranking functions differ as follows:

Function Treatment of equal sales
ROW_NUMBER Assigns each row a different position
RANK Gives ties the same rank, then leaves a gap
DENSE_RANK Gives ties the same rank, without a gap

These are PostgreSQL’s documented ranking behaviors. (postgresql.org)

For the sample data, selected output rows are:

Date Sales Row position Sales rank Dense sales rank
2026-01-09 80 1 1 1
2026-01-02 20 6 6 6
2026-01-03 20 7 6 6
2026-01-01 10 8 8 7

Notice that sale_date appears in the ROW_NUMBER ordering but not in the other two windows. It provides a deterministic tie-breaker for positions. Adding it to RANK would make the two equal-sales dates distinct ordering groups, removing their shared rank. Rankings identify ties using all window ordering expressions. (postgresql.org)

Choose ROW_NUMBER when you need exactly three rows per store. Choose RANK when the requirement is to include ties at the cutoff; that can return more than three rows. To filter a calculated ranking, put the calculation in a subquery or common table expression, then filter its result. (postgresql.org)

4. Calculate seven calendar days—not merely seven rows

This query makes the distinction visible:

SELECT
    store,
    sale_date,
    sales,
    SUM(sales) OVER (
        PARTITION BY store
        ORDER BY sale_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS seven_rows_total,
    SUM(sales) OVER (
        PARTITION BY store
        ORDER BY sale_date
        RANGE BETWEEN INTERVAL '6 days' PRECEDING
                  AND CURRENT ROW
    ) AS seven_day_total
FROM daily_sales
ORDER BY store, sale_date;

ROWS measures record positions. An offset RANGE frame measures distance between ordering values; PostgreSQL supports interval offsets for date and timestamp ordering. (postgresql.org)

Expected results:

Date Sales Seven rows total Seven-day total
2026-01-01 10 10 10
2026-01-02 20 30 30
2026-01-03 20 50 50
2026-01-05 40 90 90
2026-01-06 50 140 140
2026-01-07 60 200 200
2026-01-08 70 270 260
2026-01-09 80 340 320

On January 8, the date-based window covers January 2–8:

20 + 20 + 0 + 40 + 50 + 60 + 70 = 260

The seven-row window also includes January 1 because January 4 has no record:

10 + 20 + 20 + 40 + 50 + 60 + 70 = 270

Use six preceding days, not seven, because the current date is included.

Also write the frame explicitly. An ordered SUM with the default frame produces a running-total style calculation, not a fixed seven-day total. (postgresql.org)

This example uses dates. A timestamp-relative interval is a different reporting definition; establish the business date before calculating calendar-day metrics.

5. Add missing calendar dates when the report needs them

The date-based query calculates the correct interval for existing rows, but it does not create a January 4 output row.

For a daily chart or complete date table, build a calendar spine: a row for every date in the reporting period. PostgreSQL’s generate_series can generate the sequence. (postgresql.org)

CREATE TEMP VIEW daily_calendar AS
WITH stores AS (
    SELECT DISTINCT store
    FROM daily_sales
),
calendar AS (
    SELECT DATE '2026-01-01' + n AS sale_date
    FROM generate_series(0, 8) AS g(n)
)
SELECT
    st.store,
    c.sale_date,
    CASE
        WHEN s.store IS NULL THEN 0::numeric
        ELSE s.sales
    END AS sales
FROM stores AS st
CROSS JOIN calendar AS c
LEFT JOIN daily_sales AS s
    ON s.store = st.store
   AND s.sale_date = c.sale_date;

The cross join creates every store-date combination. The left join retains those combinations even when the sales table has no matching row. (postgresql.org)

Here, converting an absent record to zero is justified by the exercise’s stated assumption. The CASE preserves an existing row whose sales amount is NULL; it does not silently replace that unknown amount.

Now calculate the total:

SELECT
    store,
    sale_date,
    sales,
    SUM(sales) OVER (
        PARTITION BY store
        ORDER BY sale_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS seven_day_total
FROM daily_calendar
ORDER BY store, sale_date;

With one row per store for every date, seven rows now represent seven consecutive calendar dates. January 4 appears with sales of zero and a rolling total of 50.

For production work, use an authoritative store list when stores without any sales must appear. Restrict the calendar to each store’s relevant operating dates rather than assuming every store existed throughout the period.

6. Treat NULLs and incomplete history as separate problems

A zero means a known amount of nothing. A NULL represents an unknown or absent value. Do not replace one with the other without a documented reason.

PostgreSQL SUM ignores null inputs. If a frame contains no non-null amounts, the result is NULL, not zero. Compare COUNT(*) with COUNT(sales) to identify frames containing unknown amounts. (postgresql.org)

Add these diagnostic columns to a calendar-based query:

COUNT(*) OVER w AS days_in_frame,
COUNT(sales) OVER w AS known_sales_days

Define the shared window after the FROM clause:

WINDOW w AS (
    PARTITION BY store
    ORDER BY sale_date
    ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
)

PostgreSQL supports named windows so several functions can reuse the same definition. (postgresql.org)

On a complete daily calendar:

  • Fewer than seven rows means the available frame is shorter than seven days.
  • Fewer known sales values than rows means at least one amount is unknown.
  • Seven rows alone does not prove seven known daily amounts.

At the beginning of this example, totals are partial because no earlier history was supplied. Do not label January 1’s total a fully observed seven-day result.

For rankings, NULLS LAST keeps unknown amounts below known values. PostgreSQL otherwise puts nulls first by default for descending order. This controls placement; it does not make an unknown amount a meaningful sales rank. (postgresql.org)

7. Validate the result before filtering or reporting it

Start with three practical checks.

Check the daily grain. For a real input table, this query should return no rows:

SELECT store, sale_date, COUNT(*) AS row_count
FROM daily_sales
GROUP BY store, sale_date
HAVING COUNT(*) > 1;

Check a total independently. January 9 should cover January 3–9 and total 320:

SELECT SUM(sales) AS manual_check
FROM daily_calendar
WHERE store = 'A'
  AND sale_date BETWEEN DATE '2026-01-03'
                    AND DATE '2026-01-09';

Calculate before narrowing the display period. A WHERE condition in the same query removes rows before the window calculation can see them. (postgresql.org)

For example:

WITH calculated AS (
    SELECT
        store,
        sale_date,
        SUM(sales) OVER (
            PARTITION BY store
            ORDER BY sale_date
            ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
        ) AS seven_day_total
    FROM daily_calendar
)
SELECT *
FROM calculated
WHERE sale_date >= DATE '2026-01-08'
ORDER BY store, sale_date;

This displays January 8 and 9 while retaining the earlier dates needed to calculate their totals. When restricting source data for a larger report, include six preceding calendar dates as calculation history.

Finally, inspect ties, date gaps, unknown amounts, and early partial windows—not just the largest total. A ranking describes relative position; a rolling total describes a specified interval. Neither, by itself, explains why sales changed.