Skip to content

Chapter 11 — The Morning Revenue Digest#

Act III · Chapter 11 Month 2 · 06:00 9 min readDifficulty 3 of 5

Subtotals, grand totals and top-N per group without pulling a single row into Python.

FILTER (WHERE …)ROLLUPGROUPING()window framesqualify()
▶ Run it yourself · examples/171_analytics_revenue_report.py
Month 2, 06:00. Coffee is brewing. Porto's first bookings are in, and Management wants a multi-city revenue digest on their desk.

Month 2, 06:00. Coffee is brewing. Porto's first bookings are in, and Management wants a multi-city revenue digest on their desk.

Management: "City subtotals, peanut-bar revenue, grand total, AND the single largest charge in every city. By 06:15."

Panda: Fetch every Charge row into Python, loop over them with a defaultdict, sort each city list in memory, slice [:1], and sum everything again for the grand total!

Maya: Or ask PostgreSQL. It has ROLLUP, FILTER, window functions, and QUALIFY — and ships back five finished summary rows instead of five million charges.

The mission#

Pulling raw financial ledgers across the wire just to group, sum, and rank them in Python wastes bandwidth, RAM, and CPU. Maya builds Management's entire morning digest inside PostgreSQL using typed ORM analytics primitives:

  1. Multi-city subtotals + grand total + conditional sum in one query via pg.rollup(), pg.grouping(), and .filter(...) (FILTER (WHERE ...)),
  2. Top-1 charge per city + running total + ticket bucket via pg.row_number().over(...), pg.rows_between(...), pg.case(...), and .qualify(...).

The Panda's plan

charges = await pool.all(pg.select(Charge)) followed by 60 lines of nested Python for-loops, itertools.groupby, and Decimal accumulators. Works fine with 4 charges in dev; OOM-kills the web worker six months later when the ledger hits 4 million rows.

1. Seed two cities (Lisbon and Porto)#

First, our example adds Porto alongside Lisbon with a mix of room nights, peanut bar tabs, and a Douro river mud bath:

examples/171_analytics_revenue_report.py · seed_multi_city_folios
async def seed_multi_city_folios(pool: pg.Pool, lisbon: Dormitory, guests: list[Guest]) -> None:
    porto = await pool.one(
        pg.insert(Dormitory)
        .values(
            Dormitory(
                code="OPO",
                name="The Elephant Dormitory — Porto",
                city="Porto",
                country="PT",
                timezone="Europe/Lisbon",
                opened_on=date(2025, 3, 1),
            )
        )
        .returning(Dormitory)
    )
    b_lis, b_opo = await pool.all(
        pg.insert_many(
            Booking,
            [
                Booking(
                    dormitory_id=lisbon.dormitory_id,
                    primary_guest_id=guests[0].guest_id,
                    stay=pg.Range(lower=date(2026, 7, 1), upper=date(2026, 7, 4)),
                    reference_code="REV-LIS-1",
                ),
                Booking(
                    dormitory_id=porto.dormitory_id,
                    primary_guest_id=guests[2].guest_id,
                    stay=pg.Range(lower=date(2026, 7, 2), upper=date(2026, 7, 5)),
                    reference_code="REV-OPO-1",
                ),
            ],
        ).returning(Booking)
    )
    await pool.execute(
        pg.insert_many(
            Charge,
            [
                Charge(
                    booking_id=b_lis.booking_id,
                    kind=ChargeKind.NIGHTLY_RATE,
                    description="Savanna suite",
                    quantity=3,
                    unit_price=Decimal("120.00"),
                ),
                Charge(
                    booking_id=b_lis.booking_id,
                    kind=ChargeKind.PEANUT_BAR,
                    description="Roasted peanuts",
                    quantity=4,
                    unit_price=Decimal("10.00"),
                ),
                Charge(
                    booking_id=b_opo.booking_id,
                    kind=ChargeKind.NIGHTLY_RATE,
                    description="Mammoth loft",
                    quantity=2,
                    unit_price=Decimal("220.00"),
                ),
                Charge(
                    booking_id=b_opo.booking_id,
                    kind=ChargeKind.MUD_SPA,
                    description="Douro river mud bath",
                    quantity=1,
                    unit_price=Decimal("90.00"),
                ),
            ],
        )
    )

2. ROLLUP, FILTER, window frames, and QUALIFY#

Now both reports run directly on PostgreSQL in two crisp typed queries — zero raw SQL strings:

examples/171_analytics_revenue_report.py · run_revenue_reports
async def run_revenue_reports(pool: pg.Pool) -> None:
    # 1. ROLLUP + GROUPING + FILTER (WHERE ...) computes city subtotals and grand total in 1 query.
    peanut_rev = (
        pg.sum(Charge.amount).filter(Charge.kind == ChargeKind.PEANUT_BAR).alias("peanut_rev")
    )
    rollup_q = (
        pg.select(Charge)
        .join(Booking, require_using=True)
        .join(Dormitory, require_using=True)
        .columns(
            Dormitory.city,
            pg.grouping(Dormitory.city).alias("is_total"),
            pg.sum(Charge.amount).alias("gross"),
            peanut_rev,
        )
        .group_by(pg.rollup(Dormitory.city))
        .order_by(pg.col_ref("is_total").asc(), Dormitory.city.asc(nulls_last=True))
    )
    print("ROLLUP revenue by city:")
    # => ROLLUP revenue by city:
    for city, is_total, gross, peanuts in await pool.all(rollup_q):
        label = "ALL CITIES" if is_total else city
        print(f"  {label}: gross=EUR {gross}, peanuts=EUR {peanuts or Decimal('0.00')}")
        # =>   Lisbon: gross=EUR 400.00, peanuts=EUR 40.00
        # =>   Porto: gross=EUR 530.00, peanuts=EUR 0.00
        # =>   ALL CITIES: gross=EUR 930.00, peanuts=EUR 40.00

    # 2. Window functions + running frame + CASE + .qualify(rn == 1) for top charge per city.
    rn = (
        pg.row_number()
        .over(
            partition_by=[Dormitory.city],
            order_by=[Charge.amount.desc(), Charge.charge_id.asc()],
        )
        .alias("rn")
    )
    running_city = (
        pg.sum(Charge.amount)
        .over(
            partition_by=[Dormitory.city],
            order_by=[Charge.amount.desc(), Charge.charge_id.asc()],
            frame=pg.rows_between(
                pg.enums.FrameBoundKind.UNBOUNDED_PRECEDING, pg.enums.FrameBoundKind.CURRENT_ROW
            ),
        )
        .alias("running")
    )
    bucket = pg.case(
        (Charge.amount >= Decimal("200.00"), "mammoth_ticket"),
        else_="regular_ticket",
    ).alias("bucket")

    top_q = (
        pg.select(Charge)
        .join(Booking, require_using=True)
        .join(Dormitory, require_using=True)
        .columns(Dormitory.city, Charge.description, Charge.amount, bucket, rn, running_city)
        .qualify(rn == 1)
        .order_by(Dormitory.city.asc())
    )
    print("Top charge per city (QUALIFY rn = 1):")
    # => Top charge per city (QUALIFY rn = 1):
    for top_city, desc, amount, tier, _, run_tot in await pool.all(top_q):
        print(f"  {top_city}: {desc} = EUR {amount} [{tier}] (running={run_tot})")
        # =>   Lisbon: Savanna suite = EUR 360.00 [mammoth_ticket] (running=360.00)
        # =>   Porto: Mammoth loft = EUR 440.00 [mammoth_ticket] (running=440.00)

What just happened

  • pg.sum(Charge.amount).filter(Charge.kind == ChargeKind.PEANUT_BAR) compiles to PostgreSQL's crisp SQL-standard SUM("charge"."amount") FILTER (WHERE "charge"."kind" = $1) — no ugly SUM(CASE WHEN ...) boilerplate.
  • .group_by(pg.rollup(Dormitory.city)) computes per-city rows plus the ALL CITIES grand total in a single scan. pg.grouping(Dormitory.city) returns 1 on the rollup subtotal row and 0 on real cities, so you never confuse a grand total with a NULL city!
  • In the second query, pg.row_number().over(partition_by=[Dormitory.city], ...) ranks charges within each city, while pg.sum(Charge.amount).over(..., frame=pg.rows_between(pg.enums.FrameBoundKind.UNBOUNDED_PRECEDING, pg.enums.FrameBoundKind.CURRENT_ROW)) maintains a running city total.
  • .qualify(rn == 1) keeps only the top charge per city! Because PostgreSQL does not have native QUALIFY syntax yet, pgdorm's Rust compiler automatically wraps the window query in a clean subquery (SELECT * FROM (...) AS _q WHERE "rn" = $1) so your Python stays flat and readable.

Look at the actual ROLLUP SQL PostgreSQL received:

-- captured live from PostgreSQL · examples/__wire__/analytics_revenue_report.sql
SELECT
  "dormitory"."city",
  GROUPING("dormitory"."city") AS "is_total",
  SUM("charge"."amount") AS "gross",
  SUM("charge"."amount") FILTER (WHERE "charge"."kind" = $1) AS "peanut_rev"
FROM "charge"
INNER JOIN "booking" USING ("booking_id")
INNER JOIN "dormitory" USING ("dormitory_id")
GROUP BY ROLLUP ("dormitory"."city")
ORDER BY "is_total" ASC, "dormitory"."city" ASC NULLS LAST;
Ferris' basement: how .qualify() compiles cleanly on PostgreSQL

SQL evaluates WHERE before window functions (ROW_NUMBER(), RANK(), LAG()), so you can't write WHERE row_number() OVER (...) = 1 directly in PostgreSQL. .qualify(rn == 1) gives you the ergonomic single-level API while the Rust compiler lowers it into a derived table with the exact outer WHERE predicate and preserved ORDER BY.

What PostgreSQL actually received#

🔭 What PostgreSQL received: 10 statements in 9 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/analytics_revenue_report.sql

-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row

-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
  ($1, $2, $3, $4, $5, $6, $7, $8),
  ($9, $10, $11, $12, $13, $14, $15, $16),
  ($17, $18, $19, $20, $21, $22, $23, $24),
  ($25, $26, $27, $28, $29, $30, $31, $32),
  ($33, $34, $35, $36, $37, $38, $39, $40),
  ($41, $42, $43, $44, $45, $46, $47, $48),
  ($49, $50, $51, $52, $53, $54, $55, $56),
  ($57, $58, $59, $60, $61, $62, $63, $64),
  ($65, $66, $67, $68, $69, $70, $71, $72),
  ($73, $74, $75, $76, $77, $78, $79, $80),
  ($81, $82, $83, $84, $85, $86, $87, $88),
  ($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows

-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows

-- ── round trip 4 ──
COMMIT;

-- ── round trip 5 ──
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row

-- ── round trip 6 ──
INSERT INTO "booking" ("dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5
FROM unnest($1, $2, $3, $4, $5, $6) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, ord)
ORDER BY u.ord
RETURNING "booking_id", "dormitory_id", "primary_guest_id", "status", "channel", "stay", "reference_code", "created_at";
-- → 2 rows

-- ── round trip 7 ──
INSERT INTO "charge" ("booking_id", "kind", "description", "quantity", "unit_price")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4
FROM unnest($1, $2, $3, $4, $5) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, ord)
ORDER BY u.ord;
-- → 4 affected

-- ── round trip 8 ──
SELECT
  "dormitory"."city",
  GROUPING("dormitory"."city") AS "is_total",
  SUM("charge"."amount") AS "gross",
  SUM("charge"."amount") FILTER (WHERE "charge"."kind" = $1) AS "peanut_rev"
FROM "charge"
INNER JOIN "booking" USING ("booking_id")
INNER JOIN "dormitory" USING ("dormitory_id")
GROUP BY ROLLUP ("dormitory"."city")
ORDER BY "is_total" ASC, "dormitory"."city" ASC NULLS LAST;
-- → 3 rows

-- ── round trip 9 ──
SELECT *
FROM (
SELECT
  "dormitory"."city",
  "charge"."description",
  "charge"."amount",
  CASE WHEN "charge"."amount" >= $1 THEN $2 ELSE $3 END AS "bucket",
  ROW_NUMBER() OVER (PARTITION BY "dormitory"."city" ORDER BY "charge"."amount" DESC, "charge"."charge_id" ASC) AS "rn",
  SUM("charge"."amount") OVER (PARTITION BY "dormitory"."city" ORDER BY "charge"."amount" DESC, "charge"."charge_id" ASC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS "running"
FROM "charge"
INNER JOIN "booking" USING ("booking_id")
INNER JOIN "dormitory" USING ("dormitory_id")
) AS "_q"
WHERE "rn" = $4
ORDER BY "city" ASC;
-- → 2 rows

Shift report

  • Computed conditional aggregates cleanly with .filter(...) (FILTER (WHERE ...))
  • Produced per-city subtotals and a grand total in one scan with pg.rollup() + pg.grouping()
  • Ranked and accumulated per-partition running totals with .over() and pg.rows_between()
  • Classified amounts with typed pg.case(...)
  • Filtered window results cleanly with .qualify(rn == 1)

Try it yourself

Change .qualify(rn == 1) in run_revenue_reports to .qualify(rn <= 2) and watch how the running total column (running) accumulates across both charges in each city.

Go deeper: tests/integration/analytics/test_rollup_and_grouping.py · tests/integration/analytics/test_windows_and_qualify.py (live PostgreSQL test suites & snapshots)

Note

Also in pgdorm: Combine inline Select.qualify(...) with pg.cube(...), pg.grouping_sets(...), and ordered-set aggregates like percentile_cont (WITHIN GROUP) — see the Queries & DML Reference.

Sticky note from Management

"Madrid opens next quarter! Organize all dormitories into a European region tree (Europe → Iberia → Portugal → Lisbon Coast, etc.) and show me which regions don't have a hostel yet."