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_tsis a valid ISO-8601 UTC timestamp string;amountis a valid decimal string (positive, zero, or negative). - Target runtime:
O(T + W)time andO(T + W)space forTtransactions andWoutput weeks.
Step-by-step walkthrough
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:
transactionsrecords[user_id, event_ts, amount]whereevent_tsis a UTC instant andamountis a two-decimal string like'15.00'; plus LA-local range endpointsstart_dateandend_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 containingstart_datethrough the week containingend_date, sorted chronologically. - Warm-up history prior tostart_date: the 3-week trailing total spans the current week and the two immediately preceding full calendar weeks, sofirst_weekstill incorporates any activity fromfirst_week - 1 weekandfirst_week - 2 weeks. - Timestamp authority: events are bucketed strictly byevent_ts.Convert UTC instants to Los Angeles wall-clock time BEFORE bucketing
Each
event_tsis recorded in UTC, whereas week boundaries run Monday00:00through Sunday23:59:59in 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+00into2025-05-12, even though Los Angeles is still at Sunday 10:30 PM (2025-05-05). Subtracting a fixed8hours also breaks because Los Angeles switches between Daylight Saving Time (UTC-7PDT from March to November) and standard time (UTC-8PST in winter).Always apply the conversion in this exact order: 1. Convert the UTC instant into
America/Los_Angeleswall-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, ordate_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)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 runningROWS BETWEEN 2 PRECEDING AND CURRENT ROWdirectly onGROUP BYoutput 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_weekcan include activity fromfirst_week - 1 weekandfirst_week - 2 weeks, generate the calendar starting 2 weeks prior tofirst_week, evaluate the 3-row window across allW + 2weeks, and applyWHERE week_start_date >= first_weekin the outerSELECT(because aWHEREin the sameSELECTexecutes before window functions).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_tshas typeTIMESTAMPTZ(a UTC point in time),t.event_ts AT TIME ZONE 'America/Los_Angeles'produces aTIMESTAMP(without time zone) showing Los Angeles wall-clock time under the proper DST offset (UTC-7orUTC-8). Applyingdate_trunc('week', ...)to that local timestamp snaps each event to its Los Angeles Monday. In theWHEREpredicate, applyingAT TIME ZONE 'America/Los_Angeles'to the constant localTIMESTAMPbounds converts LA Monday midnights back into UTCTIMESTAMPTZvalues so PostgreSQL can range-scan a B-tree index ont.event_ts.Build the Python implementation: exact `Decimal` sums and gapless loop
Now translate each stage directly into
weekly_rolling_sums:weeklyCTE ->weekly_totalsdictionary: Iterate overtransactions, computeweek_monday = la_week_start(row[1]), and addDecimal(str(row[2])). Summing withDecimalinstead offloatpreserves exact cents just like PostgreSQLNUMERIC(12,2)(avoiding0.1 + 0.2 -> 0.30000000000000004).calendar+filled+rolledCTEs -> Monday-by-Mondaywhileloop: Step byONE_WEEKfromfirst_weekthroughlast_week. Fetchcurrent_week,current_week - ONE_WEEK, andcurrent_week - 2 * ONE_WEEKfromweekly_totalswith.get(..., Decimal(0)), which automatically picks up warm-up weeks prior tofirst_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_rowsWalk 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 Sunday2025-05-11 22:30in Los Angeles, keeping it in the2025-05-05week: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.50Every row matches Example 1's output.
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 theTrecords once (parsing each timestamp and updatingweekly_totalsinO(1)average hash-table time), then step across theWMondays performing threeO(1)dictionary lookups per week. - Python space —
O(D + W)(at mostO(T + W)):weekly_totalsstores oneDecimalentry per distinct active weekD(D <= T), andoutput_rowsholdsWthree-element rows. - PostgreSQL scaling & index usage: Writing
t.event_ts >= ... AND t.event_ts < ...leavest.event_tsunwrapped on the left side (a sargable predicate, allowing PostgreSQL to range-scan a B-tree index onevent_tsrather than reading the entire table). Hashing theMmatching rows costsO(M), and left-joining plus windowing theW + 2calendar weeks costsO(W log W)time andO(W)memory.
Edge cases
- Quiet weeks (or an empty
transactionslist): Still appear withwk_amount = 0.0because rows come from the generated Monday calendar (LEFT JOIN+COALESCE), not fromtransactionsalone. - Sunday night in LA vs Monday morning in UTC: During summer (
PDT,UTC-7),Monday 06:59 UTCisSunday 23:59 LA(prior week) whereasMonday 07:00 UTCopens the new week; during winter (PST,UTC-8), that cutoff moves toMonday 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 localTIMESTAMPavoids 1-hour DST drift. - Warm-up activity prior to
start_date: Events in the two weeks beforefirst_weekcontribute to the first two output rows'rolling_3wk_amount, while events three or more weeks earlier are ignored. - Mid-week
start_dateorend_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-29through Sunday2026-01-04stays a single week because we bucket by fullDATErather than week number; negative refund strings subtract cleanly from both totals.
Common mistakes
- Truncating
event_tsbefore converting time zones:date_trunc('week', event_ts)truncates in the database session'sTimeZone(typicallyUTC), misassigning Sunday-night Los Angeles events. - Subtracting a hard-coded
8hours: Misbuckets Monday00:00–00:59LA events throughout the roughly eight months ofUTC-7Daylight Saving Time. - Filtering
week_start_date >= first_weekin the sameSELECTasSUM(...) OVER (...): Because SQL evaluatesWHEREbefore window functions, doing so discards the two warm-up weeks before the window sum can see them! Filter warm-up rows in an outerSELECT. - Using
ROWS BETWEEN 2 PRECEDINGwithout a gapless calendar:ROWScounts 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 MondayDATE. - Accumulating currency with binary
float: Binary floats introduce representation noise (0.1 + 0.2 = 0.30000000000000004); accumulate exactDecimalvalues and convert tofloatonly when emitting rows.
Alternative approaches
- PostgreSQL
RANGEinterval 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 needgenerate_series+LEFT JOINso 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_dateand computeSUM(CASE WHEN w.week_start_date = c.week_start_date THEN w.wk_amount ELSE 0 END)alongsideCOALESCE(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 JOINweekly sums aggregated by(user_id, week_start_date)withCOALESCE(..., 0), and addPARTITION BY user_idinsideOVER (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
transactionstoaccounts(user_id, tz_name)and convert dynamically viat.event_ts AT TIME ZONE a.tz_nameprior 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
Walterswk_amountfor weekWas well asrolling_3wk_amountfor weeksW,W + 1, andW + 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
- How would you adapt the PostgreSQL query to compute 3-week rolling totals separately for each user_id?
- What changes when customers span multiple regions and each account has its own local time zone?
- If offline mobile transactions can arrive several days after event_ts, how should a daily batch pipeline refresh historical rolling sums?
Similar questions
- Python Lists vs. Dicts and Streaming Messy Files
- Category Response Rates with Invitation Weighting
- Marketplace Provider-Ranking Experiment Design
- Simulating Stay and Switch Win Rates
- Numerically Stable Min, Mean, and Median
- Driving a 72-Hour Executive Rollout Recommendation Across Teams
More Thumbtack interview questions
- Python Lists vs. Dicts and Streaming Messy Files Medium
- Category Response Rates with Invitation Weighting Medium
- Marketplace Provider-Ranking Experiment Design Hard Pro
- Simulating Stay and Switch Win Rates Medium Pro
- Numerically Stable Min, Mean, and Median Medium Pro
- Driving a 72-Hour Executive Rollout Recommendation Across Teams Hard Pro
- Modeling Adjusted Regional Response-Rate Differences Medium Pro