← Problems83. Pivot revenue into a column per categoryMediumPySpark
00:00 / 20:00

Pivot revenue into a column per category

MediumNot attempted yetAsked at Deloitte, Microsoft, TCS

The monthly trading report wants one row per month and one column per product category, whether or not that category sold anything.

Input

sales sale_id bigint category string -- 'BOOKS', 'GAMES', 'TOYS', and occasionally others sold_at string -- ISO-8601 UTC, 'YYYY-MM-DDTHH:MM:SSZ' amount double -- null until the payment provider confirms

Output

One row per month that has at least one sale, with the columns:

  • month — 'YYYY-MM'
  • BOOKS, GAMES, TOYS — that month's revenue in each, rounded to 2 decimal places, and 0.0 where there was none

Categories outside those three are not reported. A month that contains only such sales still gets a row, with three zeros.

Example

monthBOOKSGAMESTOYS
2024-01100.020.050.5
2024-0215.250.00.0

Constraints

  • The three category columns are fixed. Do not let the data decide the schema — a report whose columns change when a category has a quiet month is not a report.
  • A null amount contributes nothing. It does not make the month null.
  • Row order is not graded. Column names and their order are.

Example 1two months, three categories

Input · sales
amountsale_idsold_atcategory
10012024-01-05T00:00:00ZBOOKS
50.522024-01-09T00:00:00ZTOYS
2032024-01-20T00:00:00ZGAMES
1042024-02-02T00:00:00ZBOOKS
5.2552024-02-11T00:00:00ZBOOKS
Output
monthBOOKSGAMESTOYS
2024-011002050.5
2024-0215.2500

Example 2a month with one category still reports all three

Input · sales
amountsale_idsold_atcategory
712024-03-01T00:00:00ZTOYS
322024-03-15T00:00:00ZTOYS
Output
monthBOOKSGAMESTOYS
2024-030010

Topics

aggregationtime intelligence

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.py
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.