Spaces:
Runtime error
Runtime error
File size: 11,687 Bytes
aaef24a 9583f97 aaef24a 9583f97 aaef24a 806c8fe aaef24a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | # /// script
# requires-python = ">=3.13"
# dependencies = [
# "marimo",
# "marimo-learn>=0.12.0",
# "polars==1.24.0",
# "sqlalchemy",
# ]
# ///
import marimo
__generated_with = "0.20.4"
app = marimo.App(width="medium")
@app.cell(hide_code=True)
def _():
import marimo as mo
import marimo_learn as mol
import sqlalchemy
db_path = mol.localize_file(
"penguins.db",
"https://raw.githubusercontent.com/marimo-team/learn/main/sql/public/penguins.db"
)
DATABASE_URL = f"sqlite:///{db_path}"
engine = sqlalchemy.create_engine(DATABASE_URL)
return engine, mo, mol
@app.cell(hide_code=True)
def _():
from marimo_learn import FlashcardWidget, LabelingWidget
return FlashcardWidget, LabelingWidget
@app.cell(hide_code=True)
def _():
mo.md(r"""
# Aggregating and Grouping
The queries we wrote in the previous two tutorials operated on each row separately. We often want to ask questions about groups of rows, such as "how heavy is the largest penguin we weighed?" or "how many Gentoo penguins did we see?" This tutorial looks first at how to write queries that **aggregate** data, and then at how to calculate aggregate values for several subsets of our data simultaneously.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
## Aggregation
Let's start by finding out how heavy the heaviest penguin in our dataset is. To do this, we use a function called `max`, and give it the name of the column it is to get data from. To make the result more readable, we will use `as` to call the result `heaviest`.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select max(body_mass_g) as heaviest from penguins;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
The query below shows the six most commonly used aggregation functions in SQL applied to different columns of the penguins data.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select
avg(flipper_length_mm) as averagest,
count(species) as num_penguins,
max(body_mass_g) as heaviest,
min(flipper_length_mm) as shortest,
sum(body_mass_g) as total_mass
from penguins;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> How much do the penguins weigh in total?
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> The function `length` calculates the number of characters in a piece of text. Write a query that returns the length of the longest island name in the database.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> The function `round` rounds off a number, e.g., `round(1.234, 1)` produces `1.2`. Use this to display the average flipper length of all the penguins rounded to one decimal place.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
Note: rather than writing `count(species)` or `count(island)`, we often write `count(*)` to count the total number of rows. However, as we will see in the next tutorial `count(species)` and `count(*)` can sometimes produce slightly different answers.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
## Grouping
The query shown above applies the aggregation function to all of the rows in the table. If we want, we can apply it to just the first ten.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select avg(body_mass_g) as avg_mass
from penguins
limit 10;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
The order of operations here is important. We aren't asking SQL to calculate an average and then give us the first ten rows of the result. Instead, we are asking it to get the first ten rows and *then* calculate the average of those. This matters more when we use `where` to filter the data: the filtering happens before SQL applies the function, which lets us do things like calculate the average mass of all the Gentoo penguins.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select avg(body_mass_g) as avg_mass
from penguins
where species = 'Gentoo';
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
But what if we want to calculate the average mass for all of the species? We could write three queries, one for each species, but (a) that would be annoying and (b) if someone adds Emperor penguins to the data and we don't remember to update our query, we won't get the full picture.
What we should do instead is tell SQL to group the data based on the values in one or more columns, and then calculate the aggregate value within each group.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select avg(body_mass_g) as avg_mass
from penguins
group by species;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
Since there are three species, we get three rows of output. Unfortunately, we don't know which average corresponds to which species. To get that, we add the `species` column to the `select` clause.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select species, avg(body_mass_g) as avg_mass
from penguins
group by species;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
And just as we can order data by multiple columns at once, we can group by multiple columns. When we do, we get one bucket for each unique combination of grouping values.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select species, sex, avg(body_mass_g) as avg_mass
from penguins
group by species, sex;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
We will explain what the blanks in the `sex` column mean in the next tutorial.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> How many penguins of each sex were found on each island?
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> What is difference in weight between the heaviest female penguin and the lightest female penguin within each species?
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> Explain what the query below is calculating, and when its result would be useful.
>
> ```sql
> select round(body_mass_g/1000, 1) as weight, count(*)
> from penguins
> group by weight;
> ```
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
## Arbitrary Choice in Aggregation
The query shown below is legal SQL, but probably not what anyone would want.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select sex, species, body_mass_g
from penguins
group by species;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
The rule that SQL follows is this: if we have created groups using `group by`, and we _don't_ specify how to combine the values in a group for a particular column, then the database picks one of the values for that column in that group arbitrarily. For example, since we only grouped by `species`, but we're asking to show `sex`, the result shows one of the values for `sex` for each species. Similarly, since we didn't specify how to combine the various body masses for each species, the three values shown each come from a penguin of that species, but we don't know (and can't control) which one.
We used this behavior earlier when we selected `species` and `avg(body_mass_g)` after grouping by `species`. Since all of the penguins within a group are of the same species, it doesn't matter which `species` value the database shows us for that group: they're all the same. If we forget to choose an aggregation function by accident, though, the answer will be plausible (because it's an actual value) but wrong.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
## Filtering After Aggregation
Just as we can use `where` to filter individual rows before aggregating (or if we're not aggregating at all), we can use `having` to filter aggregated values. For example, the query below finds those combinations of sex and species whose average weight is 4kg or more.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select sex, species, avg(body_mass_g) as avg_mass
from penguins
group by sex, species
having avg_mass >= 4000.0;
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
> Explain what the query below is calculating.
>
> ```sql
> select max(flipper_length_mm) as long_flipper, species, sex
> from penguins
> where sex = 'FEMALE'
> group by species, sex
> having long_flipper > 210.0;
> ```
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
What we *can't* do with the tools we've seen so far is compare individual values to aggregates. For example, we can't use a query like the one below to find penguins that are heavier than average.
""")
return
@app.cell
def _(penguins):
_df = mo.sql(
f"""
select * from penguins
where body_mass_g > avg(body_mass_g);
""",
engine=engine
)
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
We will see how to write this query in a couple of tutorials.
""")
return
@app.cell(hide_code=True)
def _():
mo.md(r"""
## Check Understanding

""")
return
@app.cell(hide_code=True)
def _(FlashcardWidget, mo):
_widget = mo.ui.anywidget(
FlashcardWidget(
question="SQL Aggregation Functions",
cards=[
{"front": "avg(column)", "back": "Returns the average of all non-null values in the column"},
{"front": "count(*)", "back": "Counts the total number of rows, including rows with null values"},
{"front": "count(column)", "back": "Counts the number of non-null values in the column (rows with null are skipped)"},
{"front": "max(column)", "back": "Returns the largest non-null value in the column"},
{"front": "min(column)", "back": "Returns the smallest non-null value in the column"},
{"front": "sum(column)", "back": "Adds up all non-null values in the column"},
],
)
)
_widget
return
@app.cell(hide_code=True)
def _(LabelingWidget, mo):
_widget = mo.ui.anywidget(
LabelingWidget(
question="Drag each label to the line of the query it best describes.",
labels=["aggregation function", "alias", "source table", "grouping column"],
text_lines=[
"select species, avg(body_mass_g) as avg_mass",
"from penguins",
"group by species;",
],
correct_labels={0: [0, 1], 1: [2], 2: [3]},
)
)
_widget
return
if __name__ == "__main__":
app.run()
|