BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Intermediate · Lesson 6 of 12

Software Architecture

Use Windows to Explain Customer Behavior

Two coffee receipts share a minute and a price. Trace each customer’s running spend and rank their purchases without losing a single receipt.

Two rows of kraft coffee bags and receipt slips beside an espresso cup on a wooden counter.

Receipt 33 is for AED 60. The next receipt, number 34, is also for AED 60, from the same customer at the same recorded minute. The owner of a coffee roastery wants a purchase history that answers two questions beside each receipt. How much had this customer spent by this purchase? Where does the purchase rank among that customer's orders by value? The till report shows AED 160 beside both receipts. Is that a discrepancy, or did someone ask the database a different question?

Pull the receipts before deciding. The customer had spent AED 40 on an earlier visit. If we process the two new receipts one at a time, the totals should be 100 and 160. If we ask how much the customer spent through the end of that minute, 160 is right for both. And if the question is which of the purchases was more valuable, they tie. We need three decisions about ordering in a report that at first looked like a simple sum.

اقرأ الدرس بالعربية

Build a history small enough to check on paper

Run the following setup in a fresh PostgreSQL session. Each row is one settled receipt, and each amount is in whole dirhams. The customer codes identify loyalty accounts. The times are local shop times in one time zone. The shop records them only to the minute in this sample. Two different rows can therefore share a customer, time and amount. The receipt number is the evidence that these were separate checkouts.

CREATE TEMP TABLE coffee_orders (
  receipt integer PRIMARY KEY,
  customer text NOT NULL,
  paid_at timestamp NOT NULL,
  aed integer NOT NULL CHECK (aed > 0)
);
INSERT INTO coffee_orders VALUES
  (31,'A','2026-11-30 16:00',40),
  (32,'B','2026-11-30 17:00',90),
  (33,'A','2026-12-01 09:00',60),
  (34,'A','2026-12-01 09:00',60),
  (35,'B','2026-12-01 10:00',30),
  (36,'A','2026-12-02 08:00',20);

Draw two columns on paper, one for A and one for B. Under A, write the receipt numbers 31, 33, 34 and 36. Under B, write 32 and 35. Keep the purchase dates and amounts next to those numbers. If you group by customer and sum the amounts, you will get AED 180 for A and AED 120 for B. Those are useful control totals, but the two-line result cannot answer what had happened by receipt 33. We want six output rows with enough context on each row to explain its place in the history.

Agree with the owner on a convention for receipts recorded at the same time. Here we use the smaller receipt number first. This gives the report a stable sequence. It does not prove that a customer physically reached one register before another. If actual event order matters to a dispute, you need a reliable sequence from the checkout system. For the agreed reporting convention, the receipt number is unique and supplies all the tie-breaking information we need.

Add two calculations to each receipt

CREATE TEMP VIEW customer_history AS
SELECT receipt, customer, paid_at, aed,
       SUM(aed) OVER (
         PARTITION BY customer ORDER BY paid_at, receipt
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS spent_so_far,
       RANK() OVER (
         PARTITION BY customer ORDER BY aed DESC
       ) AS amount_rank
FROM coffee_orders;

SELECT customer, receipt, aed, spent_so_far, amount_rank
FROM customer_history ORDER BY customer, paid_at, receipt;

Start with the first expression. For the current receipt, the partition is every eligible receipt with the same customer code. Within that partition we arrange records by the recorded time and then the receipt number. The frame tells the sum to start at the first row of the partition and stop at the current row, inclusive. Imagine moving a bookmark down A's column. Each time it moves, add the new receipt and write the subtotal next to the bookmark. Starting B's column gives you a fresh subtotal.

The second expression reuses the idea of a customer partition but changes the ordering question. It places larger purchases first. It deliberately leaves the receipt number out of the ranking order because equal amounts should share a place. The final order of the displayed report is a third decision. We show each customer's receipts chronologically even though one of the calculations needs to compare them by amount. PostgreSQL explains how window functions keep each detail row in its window function tutorial.

Customer Receipt Paid (AED) Spent so far (AED) Rank by amount
A 31 40 40 3
A 33 60 100 1
A 34 60 160 1
A 36 20 180 4
B 32 90 90 1
B 35 30 120 2

Cover the last two columns and reconstruct them for receipt 31. It was the first purchase in A's history, so the running total is 40. Two purchases are larger, so its amount rank is three. The later purchases affect the rank of this earlier receipt. They do not affect its running total because they lie beyond the end of its chronological frame. That distinction matters if the owner wants to explain what staff could have known on the day. This rank compares the receipt with the entire history present in the table today.

Diagnose the equal timestamps

SELECT receipt, aed,
       SUM(aed) OVER (PARTITION BY customer ORDER BY paid_at)
         AS through_timestamp
FROM coffee_orders WHERE customer = 'A'
ORDER BY paid_at, receipt;

Read the results for 33 and 34. Both show 160. Removing the receipt number from the window order makes these rows peers because their timestamps are equal. With an ordered sum and the default frame, PostgreSQL includes the other rows tied at the current ordering value. At nine o'clock the calculation can therefore include both sixties, along with the earlier forty. Ordering the final display by receipt number arranges the two printed lines neatly but does nothing to change the values the window already calculated. The window expression reference specifies the frame boundaries.

Try changing just the frame to an explicit row-by-row frame while leaving only the timestamp in the window order. One of the tied purchases will now produce 100 and the other 160, but you have given no rule for which receipt gets which number. A result that happens to look right in a small test is a weak basis for reconciling a statement next month. In the saved view, the frame gives the sum its row-by-row meaning and the unique secondary order assigns each subtotal to a particular receipt.

Decide how many winners a question allows

For customer A the ordered amounts are 60, 60, 40 and 20. Competition ranking gives positions one, one, three and four. Two purchases occupy the first two positions, which explains the gap. Dense ranking would give one, one, two and three. That version counts distinct price levels. Numbering rows would instead produce four different positions. To select exactly one winning receipt you could number by descending amount and then ascending receipt number. That rule would pick 33. The owner who promised to recognize every tied top purchase needs both 33 and 34. PostgreSQL defines these functions in its ranking function reference.

Suppose the promotion is for the top two purchases per person. Ask what happens to A's AED 40 receipt. A filter for competition rank at most two leaves it out. A filter for the two highest distinct spending amounts includes it. A request for exactly two receipts needs an ordering convention when a tie crosses the cutoff. You can settle that business question using four paper receipts before anyone has to interpret a surprising number of exported offers.

Choose the history before choosing the rows to display

The owner now asks for December purchases that tied for a customer's largest purchase across the whole recorded history. Use the view, which already calculated ranks and subtotals over November and December. An outer query can then restrict the display to the desired month and rank.

SELECT customer, receipt, aed, spent_so_far
FROM customer_history
WHERE paid_at >= '2026-12-01' AND paid_at < '2027-01-01'
  AND amount_rank = 1
ORDER BY customer, paid_at, receipt;

Only receipts 33 and 34 qualify in the starting data. Customer B spent AED 90 in November and AED 30 in December. The later purchase is within the date range, but its rank across the full history is two. Moving the December condition inside the window's input would change the question. B's AED 30 would become the top purchase of December for B, and A's first December subtotal would start at 60 instead of carrying forward the earlier 40. Use a heading that says whether the total begins with the selected month or with the customer's first recorded purchase.

Before shipping the report, compare the number of distinct receipt identifiers with the result row count. Both should equal six in the unfiltered example. If a join to product lines makes one receipt appear three times, a window sum will happily add its amount three times. Restore one row per purchase before applying the window. For a second check, compare the last chronological subtotal in each customer partition to an independent grouped sum. Avoid summing every running total in the result. That would count the earliest purchases repeatedly because they contribute to many later subtotals.

The running total also lets the roastery identify a customer's first crossing of a spending threshold. Suppose the threshold is AED 100. In this ledger every purchase is positive. Subtract the current amount from the current running total to recover the previous subtotal. Select a row when the previous subtotal is below 100 and the new subtotal is at least 100. That selects receipt 33 for A and receipt 35 for B. Returning every row with a subtotal of at least 100 would tell the cashier to issue the same reward several times. This check turns an apparently small distinction in the window definition into an observable customer experience.

Exercise: a returning customer matches a personal best

Customer B comes back for another AED 90 purchase. Predict the new receipt's subtotal and rank, the new rank of B's AED 30 receipt, and the output of the December winners query. Insert this row once and query the same view again. The view reads the updated purchases each time.

INSERT INTO coffee_orders VALUES (37,'B','2026-12-02 11:00',90);

Answer. Receipt 37 brings B to AED 210 and ties receipt 32 for first place. Receipt 35 keeps its historical running total of AED 120 but its rank drops from two to three. The December winners are now 33, 34 and 37. Receipt 32 is still tied for first and stays outside the December display. There should be seven detail rows overall and the last subtotals should be AED 180 and AED 210. Together they reconcile to AED 390 in sales, with every amount traceable to one receipt.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Commit a Transfer Atomically

A mistyped till code interrupts a transfer of AED 75. Post both ledger entries in PostgreSQL and check exactly what survives a rollback.