Brightlane's logistics team needs a forward-looking view of the global order pipeline — every order paired with the combined revenue of its two immediate successors in chronological order.
Write a query to return every order's ID, ordered-at timestamp, total amount, and the combined total_amount across that order plus the two orders placed immediately after it in the global chronological sequence.
Assumptions:
- The next-3 sum at each row covers that order plus the two orders with the smallest
ordered_atstrictly after it across the entire stream. - For the last order in the stream, the sum equals just that order's
total_amount. For the second-to-last, it covers two orders. From the third-to-last back through the start, it covers three. - The final result is sorted by
ordered_atascending.
Output:
- One row per order, with columns
id,ordered_at,total_amount, andnext_3_sum. Sorted byordered_at.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
id,
ordered_at,
total_amount,
SUM(total_amount) OVER (
ORDER BY
ordered_at ROWS BETWEEN CURRENT ROW
AND 2 FOLLOWING
) AS next_3_sum
FROM
orders
ORDER BY
ordered_at The shape
SUM(total_amount) OVER (ORDER BY ordered_at ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) is a forward-looking frame. Instead of summing the current row plus rows behind it, it sums the current row plus the next two rows in the global chronological sequence.
Clause by clause
SELECT id, ordered_at, total_amount, SUM(total_amount) OVER (ORDER BY ordered_at ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) AS next_3_sumreturns the order's identifying columns and the forward-looking sum. There's noPARTITION BY, so the window is the entire orders table;ORDER BY ordered_atsequences every order chronologically across the whole stream;ROWS BETWEEN CURRENT ROW AND 2 FOLLOWINGdeclares the frame as the current row plus the next two physical rows.FROM ordersreads every order.ORDER BY ordered_atsorts the result for display.
The trap
The window shrinks at the end of the stream, not the start. The third-to-last order sees three rows; the second-to-last sees two; the last sees one (itself). That mirror image of the usual partial-window behaviour catches people who assume the partial frame always appears at the top of the result. With FOLLOWING frames, the partial rows are at the bottom.
You practiced ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING — a forward-looking frame that covers the current record plus its next two successors in order.