InterviewPrepKit

Home / SQL / Advanced Patterns

Monthly Revenue From Timestamped Orders

medium
Solving tips
  • Bucketing timestamps by period is a job for `date_trunc('month', ts)`, which normalizes every timestamp to the first instant of its month.
  • Group and order by the truncated value, not the raw timestamp, so all rows in a month collapse together.
  • Cast the bucket to `::date` for a clean YYYY-MM-DD label and to drop the time-of-day component.

Orders arrive with a full timestamp. Roll them up into total revenue per calendar month.

Schema

CREATE TABLE orders (
  order_id    INTEGER,
  ordered_at  TIMESTAMP,
  amount      INTEGER
);

Sample data:

order_idordered_atamount
12024-01-05 09:12:00100
22024-01-20 16:45:0050
32024-02-10 11:00:00200
42024-02-15 08:30:0075
52024-03-01 00:05:00300
62024-03-30 23:59:0025

Task

Return one row per calendar month with columns month (the first day of the month, as a date) and revenue (the SUM of amount for orders in that month). Order by month ascending.

Expected output

monthrevenue
2024-01-01150
2024-02-01275
2024-03-01325
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.