SELECT user_id, order_id, ordered_on,
COUNT(*) OVER (
PARTITION BY user_id
ORDER BY ordered_on, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS orders_so_far
FROM orders
ORDER BY user_id, ordered_on, order_id;
This is what the window sees when it computes the row for order 6:
An OVER clause has up to three parts, in this order:
- PARTITION BY splits the rows into groups, like GROUP BY, but nothing collapses. Leave it out and all the rows form one partition.
- ORDER BY sorts the rows inside each partition. Ranking, LAG and LEAD need it to mean anything. It also changes what an aggregate adds up, as the frames chapter shows.
- The frame picks which rows of the partition the current row sees. Here it's
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: from the partition's first row up to the current one.
Not every function reads the frame. ROW_NUMBER, RANK, DENSE_RANK, LAG and LEAD work from the partition and its order, and ignore any frame you write. Aggregates like SUM, COUNT and AVG use it, and so do FIRST_VALUE, LAST_VALUE and NTH_VALUE.
In the editor, write SPEND_SO_FAR: the same three parts, with SUM(amount) in place of COUNT(*), so each row shows the user's spend so far.