σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SQL skill›Module 1 · Querying tables›Topic 1.2·~40 minBeginner

Aggregation and GROUP BY

Skill positionModule 1 of 3 · Topic 2 of 4
1.2 Aggregation and GROUP BY
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02One row for the whole table
  3. 03One row per group
  4. 04WHERE before, HAVING after
  5. 05What the tasks ask

AAPL has 6,699 daily bars in this table, but a risk report wants one number: its average close, or its volume per year. Aggregation turns thousands of rows into a handful, and the one question that trips people up is whether to filter before or after.

01

The idea in plain words

Where we are. The previous topic selected and filtered individual rows. Here the output has fewer rows than the input: each output row summarises a group. The next topic deals with missing values, which aggregates treat in a special way.

An aggregate function reads many rows and returns one value: count, sum, avg, min, max. Alone, it summarises the whole table. With GROUP BY the rows are first sorted into groups by the value of an expression, and the aggregate runs once per group.

DefinitionGroup

All the rows that share the same value of the GROUP BY expression. Each group becomes exactly one output row.

02

One row for the whole table

main.pyPython
# Aggregates over every AAPL bar: one output rowprint(con.sql("""    SELECT count(*) AS days, min(low) AS lowest, max(high) AS highest, round(avg(close), 2) AS mean_close1    FROM bars    WHERE symbol = 'AAPL'"""))
┌───────┬──────────┬──────────┬────────────┐
│ days  │  lowest  │ highest  │ mean_close │
│ int64 │  double  │  double  │   double   │
├───────┼──────────┼──────────┼────────────┤
│  6699 │ 0.190585 │ 344.5699 │      53.96 │
└───────┴──────────┴──────────┴────────────┘
  1. 1Four aggregates, one row. count(*) counts rows; avg(close) ignores any NULL close.
03

One row per group

List the grouping expression in GROUP BY and again in SELECT. Every column in SELECT must be either one of the grouped expressions or inside an aggregate: asking for date next to GROUP BY year(date) makes no sense, because a year has many dates.

main.pyPython
# Total volume of KO per calendar year, last three yearsprint(con.sql("""    SELECT year(date) AS year, sum(volume) AS total    FROM bars    WHERE symbol = 'KO'    GROUP BY year(date)1    ORDER BY year DESC    LIMIT 3"""))
┌───────┬────────────┐
│ year  │   total    │
│ int64 │   int128   │
├───────┼────────────┤
│  2026 │ 2746116852 │
│  2025 │ 4169819546 │
│  2024 │ 3521445384 │
└───────┴────────────┘
  1. 1One output row per year.
04

WHERE before, HAVING after

WHERE removes rows before any grouping happens, so it can only talk about single rows. HAVING removes whole groups after the aggregates are known, so it is the only place to say "keep symbols whose total volume is at least ...". Filter early with WHERE whenever you can; it means less work for the database.

main.pyPython
# WHERE keeps 2026 bars; HAVING then keeps symbols with a big enough totalprint(con.sql("""    SELECT symbol, sum(volume) AS total    FROM bars    WHERE date >= '2026-01-01'1    GROUP BY symbol    HAVING sum(volume) >= 50000000002    ORDER BY total DESC"""))
┌─────────┬────────────┐
│ symbol  │   total    │
│ varchar │   int128   │
├─────────┼────────────┤
│ AAPL    │ 8114576355 │
└─────────┴────────────┘
  1. 1Row filter, before grouping.
  2. 2Group filter, after the sums exist.
An empty input still gives one row

An aggregate with no GROUP BY always returns exactly one row, even over zero input rows: count(*) is 0 and min, max, avg are NULL. With GROUP BY an empty input has no groups, so it returns no rows. The grader checks both cases.

05

What the tasks ask

  1. 1
    `summary`Four aggregates for one symbol in a single row.
  2. 2
    `yearly_volume`GROUP BY year(date) and a sum, oldest year first.
  3. 3
    `symbol_spans` and `heavy_symbols`The first filters rows with WHERE before grouping; the second filters groups with HAVING after.

Key takeaways

  • One row per group Every selected column is grouped or aggregated.
  • WHERE rows, HAVING groups Use WHERE to shrink the input and HAVING only for conditions on aggregates.
  • An empty table still has one total No GROUP BY means exactly one row, with count 0 and NULL for the rest. Next: NULLs and dates.
Quick check
You want symbols whose average close is above 100, over 2026 bars only. Where does each condition go?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • One summary row: summary25 pts
  • GROUP BY year: yearly_volume25 pts
  • WHERE before the groups: symbol_spans25 pts
  • HAVING after the groups: heavy_symbols25 pts
Explorer · lab-2-1
▾ lab-2-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-2-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-2-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes