Typorithm · medium

Window Functions

spark-windowsparkwindowrunning-totalpartition
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Window Functions

0%

Spark SQL

Window functions like sum(amount) OVER (PARTITION BY user_id ORDER BY ts) compute running totals and rankings per group without collapsing the original rows.

A window function attaches an aggregate to every row instead of replacing the group with one row.

PARTITION BY defines independent groups; ORDER BY inside the window turns the aggregate into a cumulative, per-row running value.

Swap sum for row_number, rank, or lag to number, rank, or look back across the same window.

01

OVER (...) keeps every input row.

02

PARTITION BY scopes the window per group.

03

ORDER BY makes the aggregate cumulative.

SELECT user_id, amount, sum(amount) OVER (PARTITION BY user_id ORDER BY ts) AS running FROM tx

Read the implementation

Connect each part of the code to the concept before you type.

1. Window aggregate

sum(amount) OVER computes a sum across a window of rows without collapsing them into one.

sum(amount) OVER

2. Per-user windows

PARTITION BY user_id restarts the window for each user, so totals do not leak across users.

PARTITION BY user_id

3. Running order

ORDER BY ts makes the sum cumulative in time order — a running total up to each row.

ORDER BY ts

4. Name the column

AS running names the windowed result column on each preserved row.

AS running

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Window Functions: Lesson & Practice · Typorithm | ApplyDjinn