Typorithm · medium

groupBy & agg

groupby-aggsparkgroupbyaggregationordering
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn groupBy & agg

0%

Transformations & Actions

groupBy buckets rows by a column; agg applies accumulators like sum and avg to each group, collapsing it to one row. orderBy(desc(...)) sorts the aggregated output.

groupBy partitions the DataFrame into groups keyed by one or more columns — here every distinct country becomes a group.

agg applies aggregate functions to each group: sum("revenue").alias("total") accumulates revenue and names the column, while avg("revenue") computes the per-group mean.

Each group collapses to a single row, and orderBy(desc("total")) sorts those rows so the largest total comes first; show() then prints them.

01

groupBy buckets rows by a column.

02

agg runs accumulators like sum and avg per group.

03

orderBy(desc(...)) sorts the aggregated rows.

df.groupBy("country").agg(sum("revenue").alias("total"), avg("revenue")).orderBy(desc("total")).show();

Read the implementation

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

1. Group rows

groupBy buckets rows by the given column so each country becomes one group.

df.groupBy("country")

2. Aggregate per group

agg runs accumulators like sum and avg over each group, collapsing it to one row.

agg(sum("revenue").alias("total"), avg("revenue"))

3. Name the result

alias renames the aggregated column so you can reference it later, e.g. when ordering.

.alias("total")

4. Order the output

orderBy(desc(...)) sorts the grouped result so the highest total appears first.

orderBy(desc("total"))

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.

groupBy & agg: Lesson & Practice · Typorithm | ApplyDjinn