cswork / libraryOpen practice workspace

Coding questions · Agoda

Rank Customers by Monthly Revenue with Competition Ties

Aggregate customer revenue by month and return top competition ranks, preserving tied totals and deterministic display order.

Calculate each customer's revenue by calendar month, rank customers within each month, and return customers whose revenue rank is within a supplied limit.

Input Tables

revenue_events

ColumnTypeMeaning
event_idINTEGERPrimary key
customer_idINTEGERNon-null customer identifier
revenue_dateDATENon-null date
amountNUMERIC(14,2)Non-null, nonnegative revenue

ranking_policy(top_rank INTEGER NOT NULL) contains exactly one row with a positive integer limit.

Output Contract

Write one read-only PostgreSQL query returning month_start, customer_id, total_revenue, and revenue_rank.

Aggregate all events for a customer in the same calendar month. Rank those monthly customer totals descending with competition ranking: tied totals receive the same rank and the next rank skips positions. Return ranks less than or equal to top_rank, ordered by month_start ascending, revenue_rank ascending, and customer_id ascending. month_start is the first day of the month as a DATE.

Example

For one January, customers 1 and 2 each have total revenue 100.00, and customer 3 has 90.00. If top_rank = 2, the result includes customers 1 and 2, both with rank 1. Customer 3 has rank 3 and is excluded.

Constraints and Clarifications

  • The rank limit is an explicit input rather than an invented fixed top-customer count.
  • Ties use RANK semantics, not dense ranking or an arbitrary unique ordering.
  • The output's customer-ID tie-break controls display order only; it must not break equal-revenue ranks.
  • A customer without an event in a month has no row for that month.
  • Multiple events for the same customer and month must be summed before ranking.

Hint: Rank the aggregated rows

The ranking competition is between customer-month totals, not between individual revenue events.

Top-Ranked Customers by Monthly Revenue

Table revenue_events

columntypeconstraints
event_idINTEGERPRIMARY KEY
customer_idINTEGERNOT NULL
revenue_dateDATENOT NULL
amountNUMERIC(14,2)NOT NULL

Sample data:

amountcustomer_idevent_idrevenue_date
75.25112024-12-01
24.75122024-12-15
500.00232024-12-31
99.99542024-12-20
60.00152025-01-01
40.00162025-01-31
100.00272025-01-15
50.00382025-01-20
40.00392025-01-25
80.004102025-01-10
250.003112025-02-01
120.001122025-02-28
120.004132025-02-05
0.002142025-02-14

Table ranking_policy

columntypeconstraints
top_rankINTEGERNOT NULL

Sample data:

top_rank
2

Expected output

month_startcustomer_idtotal_revenuerevenue_rank
2024-12-012500.001
2024-12-011100.002
2025-01-011100.001
2025-01-012100.001
2025-02-013250.001
2025-02-011120.002
2025-02-014120.002

Hints

  1. The ranking competition is between customer-month totals, not between individual revenue events.