Pivot Monthly Revenue by Product Category Into a Wide Report

Last updated: November 29, 2026

Quick Overview

Given a pandas DataFrame of orders (order_date, category, revenue, status), build a report with one row per month in a requested range and one column per category, excluding cancelled orders, filling empty cells with zero, and adding total row and column.

Amazon
Data Manipulation (SQL/Python)
Data Scientist
Amazon
November 29, 2026
Data Scientist
Online Assessment
Data Manipulation (SQL/Python)
Easy

0

0

0 solved


Given a pandas DataFrame of orders (order_date, category, revenue, status), build a report with one row per month in a requested range and one column per category, excluding cancelled orders, filling empty cells with zero, and adding total row and column.

Category managers at Amazon live in month by category revenue tables, and online assessments for data roles often include a quick reshape like this. The checker is whether you know pivot_table, period handling for months, and reindexing so months with no sales still appear.

What the Interviewer Expects
  • Filter cancelled orders before aggregating
  • Convert dates to monthly periods rather than string slicing
  • Use pivot_table with aggfunc='sum' and fill_value=0
  • Reindex to the full month range so empty months show up
  • Add totals without double counting the total column
Key Topics to Cover
pivot_table
to_period
reindex
reshaping
totals
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you show each category's share of the monthly total instead of dollars?
  • How would you convert this back to long format for a plotting library?
  • What changes if revenue is in several currencies?
  • How would you add a month over month growth column per category?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data
  • orders(order_date, category, revenue, status) at order-line grain. Revenue is already in one currency.
  • Cancelled orders are excluded. Months in the requested range with no sales must still appea...
Approach

Filter, derive a monthly Period, and pivot_table with sum. pivot would fail if a month and category pair repeats, which it always does here. Then reindex on pd.period_range to add missing ...


Submit Your Answer
Markdown supported