With Spark SQL, compute monthly revenue (SUM(amount)) per calendar year and month, and ytd_revenue = cumulative revenue from January up to that month within the same year (resets every year). Only months that have orders appear; ignore orders with a NULL order_date. Sort by yr, mon.
| order_id | customer_id | region | product | qty | amount | order_date |
|---|---|---|---|---|---|---|
| 1 | 1 | N | A | 1 | 1000.0 | 2024-01-05 |
| 2 | 1 | N | A | 1 | 500.0 | 2024-01-25 |
| 3 | 1 | N | A | 1 | 700.0 | 2024-02-10 |
| 4 | 1 | N | A | 1 | 300.0 | 2024-04-01 |
| yr | mon | revenue | ytd_revenue |
|---|---|---|---|
| 2024 | 1 | 1500 | 1500 |
| 2024 | 2 | 700 | 2200 |
| 2024 | 4 | 300 | 2500 |
| order_id | customer_id | region | product | qty | amount | order_date |
|---|---|---|---|---|---|---|
| 5 | 1 | N | A | 1 | 200.0 | 2023-12-15 |
| 6 | 1 | N | A | 1 | 100.0 | 2024-01-03 |
| 7 | 1 | N | A | 1 | 50.0 | 2024-02-03 |
| yr | mon | revenue | ytd_revenue |
|---|---|---|---|
| 2023 | 12 | 200 | 200 |
| 2024 | 1 | 100 | 100 |
| 2024 | 2 | 50 | 150 |
Return columns yr, mon, revenue, ytd_revenue (yr and mon are integers), sorted by yr then mon. Use spark.sql.
Solve it in the live editor on this page — run on sample data, then submit against hidden tests.
‹ Employees Earning More Than Their Manager · Second-Highest Salary per Department (or NULL) ›
{{ totalCount }} questions · {{ shHardPct }}% Hard. Real PySpark DataFrame and Spark SQL interview questions. Write PySpark in your browser on TechTown’s Spark engine, run sample tests, then submit against hidden tests.
Guests can solve {{ freeLimit }} problems for free. Log in or sign up (free) to unlock everything, keep your streak and appear on the leaderboard. New to a topic? Learn it first in the Spark course.
{{ p.statement }}
{{ p.constraints }}
No submissions yet. Press Submit to judge your code against all tests.
The model solution and step-by-step explanation unlock when you solve this problem or after 3 unsuccessful submissions ({{ shFailsLabel }}). Struggling? Try the hints on the Question tab first.
{{ p.solution }}
Write real PySpark: from pyspark.sql import functions as F, Window, spark.sql(...). It runs in your browser on a lightweight Spark engine, and the same code runs unchanged on Databricks or any Spark cluster. Use df.show() or print() to debug.
Create your free TechTown account to unlock every problem, track your progress, bookmark questions and keep preparing for interviews.