Time-Zone Weekly Totals and 3-Week Rolling Sums

Medium · Data Manipulation (SQL/Python) · Data Scientist · HR Screen

Problem Statement

Given a log of timestamped monetary events, implement weekly_rolling_sums(transactions, start_date, end_date) to compute both the single-week total and the trailing 3-week rolling total for every calendar week in the requested date span. (In a SQL interview setting, be prepared to write the equivalent single PostgreSQL query over transactions(user_id INT, event_ts TIMESTAMPTZ, amount NUMERIC(12,2)) using CTEs, generate_series, and window functions with no temporary tables, and explain how time-zone conversion interacts with week truncation.)

Input parameters: - transactions: a list of [user_id, event_ts, amount] records, where event_ts is an ISO-8601 UTC timestamp string (for example, "2025-05-05T17:00:00+00:00") and amount is a two-decimal string (such as "15.00", possibly negative for refunds). - start_date and end_date: "YYYY-MM-DD" date strings in America/Los_Angeles local time marking the inclusive reporting window.

Aggregation rules: 1. Local Monday–Sunday weeks: Convert each UTC event_ts to America/Los_Angeles wall-clock time (observing both PST UTC-8 and PDT UTC-7 Daylight Saving Time rules) before determining its calendar date and snapping back to that week's Monday (week_start_date). Use event_ts strictly as the source of truth. 2. Complete weekly series: Emit one row [week_start_date, wk_amount, rolling_3wk_amount] in ascending chronological order for every Monday–Sunday week from the week containing start_date through the week containing end_date, inclusive. Weeks with zero matching events must still appear with wk_amount = 0.0 and contribute 0 to rolling windows. 3. Trailing 3-week rolling sum: For each reported week W, rolling_3wk_amount equals the sum of wk_amount across week W, week W - 1, and week W - 2 (three consecutive calendar weeks, including any events from the two warm-up weeks immediately preceding start_date's week). 4. Numeric precision: Accumulate decimal currency values without binary floating-point drift before returning [week_start_date_str, float(wk_amount), float(rolling_3wk_amount)].

Examples

Example 1

Input:
  transactions = [
      [101, "2025-05-05T17:00:00+00:00", "15.00"],
      [102, "2025-05-12T05:30:00+00:00", "6.25"],
      [101, "2025-05-14T19:15:00+00:00", "8.75"],
      [103, "2025-05-27T16:40:00+00:00", "14.00"],
      [102, "2025-05-29T03:20:00+00:00", "4.50"],
      [104, "2025-06-04T22:00:00+00:00", "10.00"],
  ]
  start_date = "2025-05-05"
  end_date = "2025-06-09"

Output:
  [
      ["2025-05-05", 21.25, 21.25],
      ["2025-05-12", 8.75, 30.0],
      ["2025-05-19", 0.0, 30.0],
      ["2025-05-26", 18.5, 27.25],
      ["2025-06-02", 10.0, 28.5],
      ["2025-06-09", 0.0, 28.5],
  ]

Walk-through: In May and June, Los Angeles observes PDT (UTC-7). The second event (2025-05-12T05:30:00+00:00) occurs at Sunday 2025-05-11 22:30 in Los Angeles, so its 6.25 combines with 15.00 in the 2025-05-05 week (21.25). The quiet week 2025-05-19 still appears with wk_amount = 0.0, keeping rolling_3wk_amount = 21.25 + 8.75 + 0.0 = 30.0, and 2025-05-26 sums 8.75 + 0.0 + 18.5 = 27.25.

Example 2

Input:
  transactions = [
      [1, "2025-01-08T20:00:00+00:00", "5.00"],
      [2, "2025-01-20T07:45:00+00:00", "9.00"],
      [1, "2025-01-20T08:15:00+00:00", "12.00"],
  ]
  start_date = "2025-01-22"
  end_date = "2025-01-28"

Output:
  [
      ["2025-01-20", 12.0, 26.0],
      ["2025-01-27", 0.0, 21.0],
  ]

Walk-through: Mid-week bounds "2025-01-22" (Wednesday) and "2025-01-28" (Tuesday) select the full weeks starting "2025-01-20" and "2025-01-27". In January (PST, UTC-8), "2025-01-20T07:45:00+00:00" is Sunday 23:45 (2025-01-13 week, 9.00) while "2025-01-20T08:15:00+00:00" is Monday 00:15 (2025-01-20 week, 12.00). Including the two prior warm-up weeks (5.0 from 2025-01-06 and 9.0 from 2025-01-13) gives 26.0 for 2025-01-20 and 9.0 + 12.0 + 0.0 = 21.0 for 2025-01-27.

Constraints

  • 0 <= len(transactions) <= 10^5.
  • start_date <= end_date, formatted as valid ISO "YYYY-MM-DD" dates.
  • Each event_ts is a valid ISO-8601 UTC timestamp string; amount is a valid decimal string (positive, zero, or negative).
  • Target runtime: O(T + W) time and O(T + W) space for T transactions and W output weeks.

Step-by-step walkthrough

  1. Restate the problem: PostgreSQL query + Python judge implementation

    In an interview, you may be asked to write a single PostgreSQL query (alongside a concise explanation of time-zone conversion), while the automated judge validates the identical rules in Python via weekly_rolling_sums(transactions, start_date, end_date). Let's design the PostgreSQL query first and then mirror every step in Python.

    Core contract and boundary rules: - Inputs: transactions records [user_id, event_ts, amount] where event_ts is a UTC instant and amount is a two-decimal string like '15.00'; plus LA-local range endpoints start_date and end_date (for instance '2025-05-05' and '2025-06-09'). - Outputs: one row [week_start_date, wk_amount, rolling_3wk_amount] for every Monday–Sunday week from the week containing start_date through the week containing end_date, sorted chronologically. - Warm-up history prior to start_date: the 3-week trailing total spans the current week and the two immediately preceding full calendar weeks, so first_week still incorporates any activity from first_week - 1 week and first_week - 2 weeks. - Timestamp authority: events are bucketed strictly by event_ts.

  2. Convert UTC instants to Los Angeles wall-clock time BEFORE bucketing

    Each event_ts is recorded in UTC, whereas week boundaries run Monday 00:00 through Sunday 23:59:59 in Los Angeles local time. Around midnight, a single UTC instant belongs to different calendar dates — and different weeks — in UTC versus Los Angeles:

    UTC clock:          Sun May 11 23:00  |  Mon May 12 00:00 ... Mon May 12 05:30 | Mon May 12 07:00
                                          ^ UTC enters Monday 7 hours ahead of LA!
    LA clock (PDT, -7): Sun May 11 16:00  |  Sun May 11 17:00 ... Sun May 11 22:30 | Mon May 12 00:00
    LA week_start_date: <---------------- week of 2025-05-05 --------------------> | <-- 2025-05-12 --
    

    Truncating the UTC timestamp to Monday first would misplace 2025-05-12 05:30+00 into 2025-05-12, even though Los Angeles is still at Sunday 10:30 PM (2025-05-05). Subtracting a fixed 8 hours also breaks because Los Angeles switches between Daylight Saving Time (UTC-7 PDT from March to November) and standard time (UTC-8 PST in winter).

    Always apply the conversion in this exact order: 1. Convert the UTC instant into America/Los_Angeles wall-clock time via the IANA time-zone database. 2. Take the local calendar date and step back to Monday (day - timedelta(days=day.weekday()) in Python, or date_trunc('week', ...) in PostgreSQL, which snaps to ISO Monday).

    LA_TZ = ZoneInfo("America/Los_Angeles")
    ONE_WEEK = timedelta(weeks=1)
    
    
    def monday_of(day: date) -> date:
        """Return the Monday date of the Monday-Sunday week containing `day`."""
        # date.weekday() is 0 for Monday through 6 for Sunday.
        return day - timedelta(days=day.weekday())
    
    
    def la_week_start(event_ts: str) -> date:
        """Convert a UTC ISO-8601 timestamp string to its LA-local Monday date."""
        utc_instant = datetime.fromisoformat(event_ts)
        if utc_instant.tzinfo is None:
            utc_instant = utc_instant.replace(tzinfo=timezone.utc)
        la_local_date = utc_instant.astimezone(LA_TZ).date()
        return monday_of(la_local_date)
    
  3. Why the SQL rolling window needs a gapless calendar + 2 warm-up weeks

    Suppose zero events occur during the week of 2025-05-19. Compare running ROWS BETWEEN 2 PRECEDING AND CURRENT ROW directly on GROUP BY output against joining onto a complete weekly calendar first:

    WRONG (missing 05-19 row!):               RIGHT (gapless calendar + COALESCE to 0):
    week        wk_amount   2 PRECEDING       week        wk_amount   2 PRECEDING
    ----------  ---------   -----------       ----------  ---------   ------------------------
    2025-05-05      21.25         21.25       2025-05-05      21.25   21.25
    2025-05-12       8.75         30.00       2025-05-12       8.75   21.25 + 8.75 = 30.00
    2025-05-26      18.50         48.50 <--!  2025-05-19       0.00   21.25 + 8.75 + 0 = 30.00
    (reaches back to 05-05: a 4-week span     2025-05-26      18.50   8.75 + 0 + 18.50 = 27.25
     instead of 3 calendar weeks!)            (2 physical rows back == 2 calendar weeks back!)
    

    Similarly, so that first_week can include activity from first_week - 1 week and first_week - 2 weeks, generate the calendar starting 2 weeks prior to first_week, evaluate the 3-row window across all W + 2 weeks, and apply WHERE week_start_date >= first_week in the outer SELECT (because a WHERE in the same SELECT executes before window functions).

  4. Write the complete PostgreSQL query

    WITH bounds AS (
        -- Snap range endpoints to LA-local Monday 00:00 timestamps (without time zone)
        -- so generate_series steps by exact 7-day calendar weeks independent of session TimeZone.
        SELECT date_trunc('week', DATE '2025-05-05'::timestamp) AS first_week,
               date_trunc('week', DATE '2025-06-09'::timestamp) AS last_week
    ),
    weekly AS (
        -- Convert UTC timestamptz -> LA wall-clock timestamp BEFORE truncating to Monday.
        SELECT date_trunc('week', t.event_ts AT TIME ZONE 'America/Los_Angeles')::date AS week_start_date,
               SUM(t.amount) AS wk_amount
        FROM transactions t
        CROSS JOIN bounds b
        -- Convert constant LA Monday boundaries back to UTC instants so an index on event_ts stays usable.
        WHERE t.event_ts >= (b.first_week - INTERVAL '2 weeks') AT TIME ZONE 'America/Los_Angeles'
          AND t.event_ts <  (b.last_week  + INTERVAL '1 week')  AT TIME ZONE 'America/Los_Angeles'
        GROUP BY 1
    ),
    calendar AS (
        -- Include 2 warm-up Mondays prior to first_week so the first output row has a full 3-week window.
        SELECT gs::date AS week_start_date
        FROM bounds b
        CROSS JOIN generate_series(
            b.first_week - INTERVAL '2 weeks',
            b.last_week,
            INTERVAL '1 week'
        ) AS gs
    ),
    filled AS (
        -- Left join onto the complete calendar and turn missing weeks into 0.
        SELECT c.week_start_date,
               COALESCE(w.wk_amount, 0) AS wk_amount
        FROM calendar c
        LEFT JOIN weekly w
          ON w.week_start_date = c.week_start_date
    ),
    rolled AS (
        -- Because filled has zero gaps, 2 PRECEDING rows always equals the prior 2 calendar weeks.
        SELECT week_start_date,
               wk_amount,
               SUM(wk_amount) OVER (
                   ORDER BY week_start_date
                   ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
               ) AS rolling_3wk_amount
        FROM filled
    )
    -- Drop the 2 warm-up rows AFTER the window function has already included them.
    SELECT r.week_start_date,
           r.wk_amount::NUMERIC(12,2)          AS wk_amount,
           r.rolling_3wk_amount::NUMERIC(12,2) AS rolling_3wk_amount
    FROM rolled r
    CROSS JOIN bounds b
    WHERE r.week_start_date >= b.first_week::date
    ORDER BY r.week_start_date;
    

    Time-zone conversion note: When t.event_ts has type TIMESTAMPTZ (a UTC point in time), t.event_ts AT TIME ZONE 'America/Los_Angeles' produces a TIMESTAMP (without time zone) showing Los Angeles wall-clock time under the proper DST offset (UTC-7 or UTC-8). Applying date_trunc('week', ...) to that local timestamp snaps each event to its Los Angeles Monday. In the WHERE predicate, applying AT TIME ZONE 'America/Los_Angeles' to the constant local TIMESTAMP bounds converts LA Monday midnights back into UTC TIMESTAMPTZ values so PostgreSQL can range-scan a B-tree index on t.event_ts.

  5. Build the Python implementation: exact `Decimal` sums and gapless loop

    Now translate each stage directly into weekly_rolling_sums:

    1. weekly CTE -> weekly_totals dictionary: Iterate over transactions, compute week_monday = la_week_start(row[1]), and add Decimal(str(row[2])). Summing with Decimal instead of float preserves exact cents just like PostgreSQL NUMERIC(12,2) (avoiding 0.1 + 0.2 -> 0.30000000000000004).
    2. calendar + filled + rolled CTEs -> Monday-by-Monday while loop: Step by ONE_WEEK from first_week through last_week. Fetch current_week, current_week - ONE_WEEK, and current_week - 2 * ONE_WEEK from weekly_totals with .get(..., Decimal(0)), which automatically picks up warm-up weeks prior to first_week.
    def weekly_rolling_sums(
        transactions: List[List[str]], start_date: str, end_date: str
    ) -> List[List[object]]:
        # ---- Phase 1: Bucket transactions by LA-local Monday and sum exact cents ----
        weekly_totals = {}
        for row in transactions:
            week_monday = la_week_start(row[1])
            amount = Decimal(str(row[2]))
            weekly_totals[week_monday] = weekly_totals.get(week_monday, Decimal(0)) + amount
    
        # ---- Phase 2: Walk a gapless Monday calendar and compute 3-week rolling sums ----
        first_week = monday_of(date.fromisoformat(start_date))
        last_week = monday_of(date.fromisoformat(end_date))
    
        output_rows = []
        current_week = first_week
        while current_week <= last_week:
            wk_amount = weekly_totals.get(current_week, Decimal(0))
            prev_week_1 = weekly_totals.get(current_week - ONE_WEEK, Decimal(0))
            prev_week_2 = weekly_totals.get(current_week - 2 * ONE_WEEK, Decimal(0))
            rolling_3wk_amount = wk_amount + prev_week_1 + prev_week_2
    
            output_rows.append([
                current_week.isoformat(),
                float(wk_amount),
                float(rolling_3wk_amount),
            ])
            current_week += ONE_WEEK
    
        return output_rows
    
  6. Walk through Example 1

    During May and June, Los Angeles observes PDT (UTC-7). Notice the second transaction (2025-05-12 05:30+00): although the UTC clock already reads Monday May 12, subtracting 7 hours gives Sunday 2025-05-11 22:30 in Los Angeles, keeping it in the 2025-05-05 week:

    event_ts (UTC)          LA wall-clock (UTC-7)    LA Monday    amount
    ----------------------  -----------------------  -----------  ------
    2025-05-05 17:00+00     Mon 2025-05-05 10:00     2025-05-05    15.00
    2025-05-12 05:30+00     Sun 2025-05-11 22:30     2025-05-05     6.25
    2025-05-14 19:15+00     Wed 2025-05-14 12:15     2025-05-12     8.75
    2025-05-27 16:40+00     Tue 2025-05-27 09:40     2025-05-26    14.00
    2025-05-29 03:20+00     Wed 2025-05-28 20:20     2025-05-26     4.50
    2025-06-04 22:00+00     Wed 2025-06-04 15:00     2025-06-02    10.00
    
    Calendar week   wk_amount   3-week rolling calculation         rolling_3wk_amount
    -------------   ---------   --------------------------------   ------------------
    2025-05-05          21.25   0.00  + 0.00  + 21.25                           21.25
    2025-05-12           8.75   0.00  + 21.25 + 8.75                            30.00
    2025-05-19           0.00   21.25 + 8.75  + 0.00 (empty week!)              30.00
    2025-05-26          18.50   8.75  + 0.00  + 18.50                           27.25
    2025-06-02          10.00   0.00  + 18.50 + 10.00                           28.50
    2025-06-09           0.00   18.50 + 10.00 + 0.00 (empty week!)              28.50
    

    Every row matches Example 1's output.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from datetime import date, datetime, timedelta, timezone
    from decimal import Decimal
    from zoneinfo import ZoneInfo
    
    try:
        # Ensure Pyodide / minimal OS runtimes load the IANA time-zone database if available.
        import tzdata  # noqa: F401
    except ImportError:
        pass
    
    LA_TZ = ZoneInfo("America/Los_Angeles")
    ONE_WEEK = timedelta(weeks=1)
    
    
    def monday_of(day: date) -> date:
        """Return the Monday date of the Monday-Sunday week containing `day`."""
        # date.weekday() is 0 for Monday through 6 for Sunday.
        return day - timedelta(days=day.weekday())
    
    
    def la_week_start(event_ts: str) -> date:
        """Convert a UTC ISO-8601 timestamp string to its LA-local Monday date."""
        utc_instant = datetime.fromisoformat(event_ts)
        if utc_instant.tzinfo is None:
            utc_instant = utc_instant.replace(tzinfo=timezone.utc)
        # Convert to America/Los_Angeles BEFORE taking .date() so Sunday night in LA
        # (which is already Monday morning in UTC) stays in Sunday's LA week, and so
        # ZoneInfo automatically applies PDT (UTC-7) or PST (UTC-8) for that instant.
        la_local_date = utc_instant.astimezone(LA_TZ).date()
        return monday_of(la_local_date)
    
    
    def weekly_rolling_sums(
        transactions: List[List[str]], start_date: str, end_date: str
    ) -> List[List[object]]:
        """Return `[week_start_date, wk_amount, rolling_3wk_amount]` for each LA week in range."""
        # ---- Phase 1: Bucket transactions by LA-local Monday and sum exact cents ----
        # weekly_totals: dict mapping LA Monday `date` -> `Decimal` sum of amounts in that week
        weekly_totals: Dict[date, Decimal] = {}
        for row in transactions:
            week_monday = la_week_start(row[1])
            # Sum with Decimal(str(...)) to match PostgreSQL NUMERIC(12,2) without float drift.
            amount = Decimal(str(row[2]))
            weekly_totals[week_monday] = weekly_totals.get(week_monday, Decimal(0)) + amount
    
        # ---- Phase 2: Walk a gapless Monday calendar and compute 3-week rolling sums ----
        first_week = monday_of(date.fromisoformat(start_date))
        last_week = monday_of(date.fromisoformat(end_date))
    
        output_rows: List[List[object]] = []
        current_week = first_week
        while current_week <= last_week:
            # Missing weeks default to 0, mirroring SQL's calendar LEFT JOIN + COALESCE(..., 0).
            wk_amount = weekly_totals.get(current_week, Decimal(0))
            prev_week_1 = weekly_totals.get(current_week - ONE_WEEK, Decimal(0))
            prev_week_2 = weekly_totals.get(current_week - 2 * ONE_WEEK, Decimal(0))
            # The two prior weeks count even when they fall before start_date.
            rolling_3wk_amount = wk_amount + prev_week_1 + prev_week_2
    
            output_rows.append([
                current_week.isoformat(),
                float(wk_amount),
                float(rolling_3wk_amount),
            ])
            current_week += ONE_WEEK
    
        return output_rows
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine keeping a physical wall calendar in a Los Angeles shop while your payment gateway stamps every receipt in UTC. Computing accurate 3-week sales rollups requires three steps in strict sequence: first, shift each receipt's UTC timestamp onto the Los Angeles wall clock before choosing which Monday–Sunday row it belongs on; second, write $0.00 onto any quiet week so the calendar has zero missing rows; and third, slide a 3-row ruler down the page, summing each week with the two rows right above it. In SQL, we organize those steps with CTEs (Common Table Expressions, named WITH subqueries that structure a query into readable pipeline stages) and evaluate the sliding total with a window function (an OVER (...) expression that aggregates across adjacent rows without collapsing them).

Why do shortcuts fail? Truncating event_ts to Monday before converting time zones misfiles a Sunday 10:30 PM Los Angeles purchase (Monday 05:30 UTC) into the next week! Subtracting a fixed 8 hours also breaks because Los Angeles observes Daylight Saving Time (DST) (UTC-7 in summer and UTC-8 in winter). And if you run ROWS BETWEEN 2 PRECEDING AND CURRENT ROW directly on weeks that had activity without first inserting $0 rows for quiet weeks, skipping an empty week causes "2 rows back" to reach 4 calendar weeks into the past!

Let's trace four weeks from Example 1 (2025-05-05 through 2025-05-26, summer PDT UTC-7): 1. 2025-05-12 05:30+00 converts to Sun 2025-05-11 22:30 PDT, placing its $6.25 alongside $15.00 in Monday 2025-05-05 ($21.25). 2. 2025-05-12 totals $8.75, 2025-05-19 has zero events ($0.00), and 2025-05-26 totals $18.50. 3. Over the gapless weekly sequence [21.25, 8.75, 0.0, 18.5], the 3-week sliding totals are [21.25, 30.0, 30.0, 27.25].

Complexity

Let T be the number of input transactions and W be the number of reported weeks from start_date through end_date.

  • Python time — O(T + W): We iterate over the T records once (parsing each timestamp and updating weekly_totals in O(1) average hash-table time), then step across the W Mondays performing three O(1) dictionary lookups per week.
  • Python space — O(D + W) (at most O(T + W)): weekly_totals stores one Decimal entry per distinct active week D (D <= T), and output_rows holds W three-element rows.
  • PostgreSQL scaling & index usage: Writing t.event_ts >= ... AND t.event_ts < ... leaves t.event_ts unwrapped on the left side (a sargable predicate, allowing PostgreSQL to range-scan a B-tree index on event_ts rather than reading the entire table). Hashing the M matching rows costs O(M), and left-joining plus windowing the W + 2 calendar weeks costs O(W log W) time and O(W) memory.

Edge cases

  • Quiet weeks (or an empty transactions list): Still appear with wk_amount = 0.0 because rows come from the generated Monday calendar (LEFT JOIN + COALESCE), not from transactions alone.
  • Sunday night in LA vs Monday morning in UTC: During summer (PDT, UTC-7), Monday 06:59 UTC is Sunday 23:59 LA (prior week) whereas Monday 07:00 UTC opens the new week; during winter (PST, UTC-8), that cutoff moves to Monday 08:00 UTC.
  • DST switch weeks (167-hour March week / 169-hour November week): Each TIMESTAMPTZ (PostgreSQL's UTC-anchored point-in-time type) converts using the offset valid at its exact instant, and stepping Mondays on local TIMESTAMP avoids 1-hour DST drift.
  • Warm-up activity prior to start_date: Events in the two weeks before first_week contribute to the first two output rows' rolling_3wk_amount, while events three or more weeks earlier are ignored.
  • Mid-week start_date or end_date: Both snap back to their enclosing Monday (monday_of / date_trunc('week', ...)), emitting complete Monday–Sunday weeks.
  • New-Year boundaries & negative refunds: Monday 2025-12-29 through Sunday 2026-01-04 stays a single week because we bucket by full DATE rather than week number; negative refund strings subtract cleanly from both totals.

Common mistakes

  • Truncating event_ts before converting time zones: date_trunc('week', event_ts) truncates in the database session's TimeZone (typically UTC), misassigning Sunday-night Los Angeles events.
  • Subtracting a hard-coded 8 hours: Misbuckets Monday 00:00–00:59 LA events throughout the roughly eight months of UTC-7 Daylight Saving Time.
  • Filtering week_start_date >= first_week in the same SELECT as SUM(...) OVER (...): Because SQL evaluates WHERE before window functions, doing so discards the two warm-up weeks before the window sum can see them! Filter warm-up rows in an outer SELECT.
  • Using ROWS BETWEEN 2 PRECEDING without a gapless calendar: ROWS counts result rows rather than calendar weeks, silently stretching the lookback past 21 days whenever a week is missing.
  • Grouping by EXTRACT(WEEK FROM ...) alone: ISO week numbers (1..53) repeat annually and collide across multi-year spans; always group by the Monday DATE.
  • Accumulating currency with binary float: Binary floats introduce representation noise (0.1 + 0.2 = 0.30000000000000004); accumulate exact Decimal values and convert to float only when emitting rows.

Alternative approaches

  • PostgreSQL RANGE interval window: SUM(wk_amount) OVER (ORDER BY week_start_date RANGE BETWEEN INTERVAL '14 days' PRECEDING AND CURRENT ROW) measures window width by calendar distance (14 days) instead of physical row count (2 PRECEDING), though you still need generate_series + LEFT JOIN so zero-activity weeks appear in the output.
  • PostgreSQL 14+ three-argument date_trunc: date_trunc('week', t.event_ts, 'America/Los_Angeles') truncates directly in Los Angeles time and can be cast via ( ... AT TIME ZONE 'America/Los_Angeles')::date.
  • Calendar range join (when window functions are unavailable): LEFT JOIN weekly w ON w.week_start_date BETWEEN c.week_start_date - 14 AND c.week_start_date and compute SUM(CASE WHEN w.week_start_date = c.week_start_date THEN w.wk_amount ELSE 0 END) alongside COALESCE(SUM(w.wk_amount), 0).

Follow-up questions

  • How would you adapt the PostgreSQL query to compute 3-week rolling totals separately for each user_id? Cross-join the weekly calendar (including the two warm-up weeks) with the set of target users, LEFT JOIN weekly sums aggregated by (user_id, week_start_date) with COALESCE(..., 0), and add PARTITION BY user_id inside OVER (PARTITION BY user_id ORDER BY week_start_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) so every user's 3-week window resets independently.
  • What changes when customers span multiple regions and each account has its own local time zone? Join transactions to accounts(user_id, tz_name) and convert dynamically via t.event_ts AT TIME ZONE a.tz_name prior to truncating to Monday. For executive rollups across regions, align with stakeholders on whether company-wide reports use one canonical headquarters zone (America/Los_Angeles) or sum each user's local Monday–Sunday week (which start up to a day apart globally).
  • If offline mobile transactions can arrive several days after event_ts, how should a daily batch pipeline refresh historical rolling sums? A late transaction stamped in week W alters wk_amount for week W as well as rolling_3wk_amount for weeks W, W + 1, and W + 2. Recompute a trailing recomputation window wider than your maximum late-arrival SLA plus two rolling weeks (for example, the past 5–6 weeks) each night and upsert (INSERT ... ON CONFLICT (week_start_date) DO UPDATE, inserting new weeks or overwriting revised weeks) into the target reporting table so historical figures heal idempotently.

Follow-up questions

Similar questions

More Thumbtack interview questions

All 8 Thumbtack questions →