635a7f6dfe918016023ac0c54119d539324527c5
[swc-sql.git] / sql / novice / 06-agg.ipynb
1 {
2  "metadata": {
3   "name": ""
4  },
5  "nbformat": 3,
6  "nbformat_minor": 0,
7  "worksheets": [
8   {
9    "cells": [
10     {
11      "cell_type": "heading",
12      "level": 1,
13      "metadata": {},
14      "source": [
15       "Aggregation"
16      ]
17     },
18     {
19      "cell_type": "markdown",
20      "metadata": {},
21      "source": [
22       "We now want to calculate ranges and averages for our data.\n",
23       "We know how to select all of the dates from the `Visited` table:"
24      ]
25     },
26     {
27      "cell_type": "code",
28      "collapsed": false,
29      "input": [
30       "%load_ext sqlitemagic"
31      ],
32      "language": "python",
33      "metadata": {},
34      "outputs": [],
35      "prompt_number": 1
36     },
37     {
38      "cell_type": "code",
39      "collapsed": false,
40      "input": [
41       "%%sqlite survey.db\n",
42       "select dated from Visited;"
43      ],
44      "language": "python",
45      "metadata": {},
46      "outputs": [
47       {
48        "html": [
49         "<table>\n",
50         "<tr><td>1927-02-08</td></tr>\n",
51         "<tr><td>1927-02-10</td></tr>\n",
52         "<tr><td>1939-01-07</td></tr>\n",
53         "<tr><td>1930-01-12</td></tr>\n",
54         "<tr><td>1930-02-26</td></tr>\n",
55         "<tr><td>None</td></tr>\n",
56         "<tr><td>1932-01-14</td></tr>\n",
57         "<tr><td>1932-03-22</td></tr>\n",
58         "</table>"
59        ],
60        "metadata": {},
61        "output_type": "display_data",
62        "text": [
63         "<IPython.core.display.HTML at 0x1023c4110>"
64        ]
65       }
66      ],
67      "prompt_number": 2
68     },
69     {
70      "cell_type": "markdown",
71      "metadata": {},
72      "source": [
73       "but to combine them,\n",
74       "wee must use an [aggregation function](../../gloss.html#aggregation-function)\n",
75       "such as `min` or `max`.\n",
76       "Each of these functions takes a set of records as input,\n",
77       "and produces a single record as output:"
78      ]
79     },
80     {
81      "cell_type": "code",
82      "collapsed": false,
83      "input": [
84       "%%sqlite survey.db\n",
85       "select min(dated) from Visited;"
86      ],
87      "language": "python",
88      "metadata": {},
89      "outputs": [
90       {
91        "html": [
92         "<table>\n",
93         "<tr><td>1927-02-08</td></tr>\n",
94         "</table>"
95        ],
96        "metadata": {},
97        "output_type": "display_data",
98        "text": [
99         "<IPython.core.display.HTML at 0x1023c4110>"
100        ]
101       }
102      ],
103      "prompt_number": 3
104     },
105     {
106      "cell_type": "markdown",
107      "metadata": {},
108      "source": [
109       "<img src=\"files/img/sql-aggregation.svg\" alt=\"SQL Aggregation\" />"
110      ]
111     },
112     {
113      "cell_type": "code",
114      "collapsed": false,
115      "input": [
116       "%%sqlite survey.db\n",
117       "select max(dated) from Visited;"
118      ],
119      "language": "python",
120      "metadata": {},
121      "outputs": [
122       {
123        "html": [
124         "<table>\n",
125         "<tr><td>1939-01-07</td></tr>\n",
126         "</table>"
127        ],
128        "metadata": {},
129        "output_type": "display_data",
130        "text": [
131         "<IPython.core.display.HTML at 0x1023c4190>"
132        ]
133       }
134      ],
135      "prompt_number": 4
136     },
137     {
138      "cell_type": "markdown",
139      "metadata": {},
140      "source": [
141       "`min` and `max` are just two of\n",
142       "the aggregation functions built into SQL.\n",
143       "Three others are `avg`,\n",
144       "`count`,\n",
145       "and `sum`:"
146      ]
147     },
148     {
149      "cell_type": "code",
150      "collapsed": false,
151      "input": [
152       "%%sqlite survey.db\n",
153       "select avg(reading) from Survey where quant='sal';"
154      ],
155      "language": "python",
156      "metadata": {},
157      "outputs": [
158       {
159        "html": [
160         "<table>\n",
161         "<tr><td>7.20333333333</td></tr>\n",
162         "</table>"
163        ],
164        "metadata": {},
165        "output_type": "display_data",
166        "text": [
167         "<IPython.core.display.HTML at 0x1023c37d0>"
168        ]
169       }
170      ],
171      "prompt_number": 5
172     },
173     {
174      "cell_type": "code",
175      "collapsed": false,
176      "input": [
177       "%%sqlite survey.db\n",
178       "select count(reading) from Survey where quant='sal';"
179      ],
180      "language": "python",
181      "metadata": {},
182      "outputs": [
183       {
184        "html": [
185         "<table>\n",
186         "<tr><td>9</td></tr>\n",
187         "</table>"
188        ],
189        "metadata": {},
190        "output_type": "display_data",
191        "text": [
192         "<IPython.core.display.HTML at 0x1023c37d0>"
193        ]
194       }
195      ],
196      "prompt_number": 6
197     },
198     {
199      "cell_type": "code",
200      "collapsed": false,
201      "input": [
202       "%%sqlite survey.db\n",
203       "select sum(reading) from Survey where quant='sal';"
204      ],
205      "language": "python",
206      "metadata": {},
207      "outputs": [
208       {
209        "html": [
210         "<table>\n",
211         "<tr><td>64.83</td></tr>\n",
212         "</table>"
213        ],
214        "metadata": {},
215        "output_type": "display_data",
216        "text": [
217         "<IPython.core.display.HTML at 0x1023c37d0>"
218        ]
219       }
220      ],
221      "prompt_number": 7
222     },
223     {
224      "cell_type": "markdown",
225      "metadata": {},
226      "source": [
227       "We used `count(reading)` here,\n",
228       "but we could just as easily have counted `quant`\n",
229       "or any other field in the table,\n",
230       "or even used `count(*)`,\n",
231       "since the function doesn't care about the values themselves,\n",
232       "just how many values there are.\n",
233       "\n",
234       "SQL lets us do several aggregations at once.\n",
235       "We can,\n",
236       "for example,\n",
237       "find the range of sensible salinity measurements:"
238      ]
239     },
240     {
241      "cell_type": "code",
242      "collapsed": false,
243      "input": [
244       "%%sqlite survey.db\n",
245       "select min(reading), max(reading) from Survey where quant='sal' and reading<=1.0;"
246      ],
247      "language": "python",
248      "metadata": {},
249      "outputs": [
250       {
251        "html": [
252         "<table>\n",
253         "<tr><td>0.05</td><td>0.21</td></tr>\n",
254         "</table>"
255        ],
256        "metadata": {},
257        "output_type": "display_data",
258        "text": [
259         "<IPython.core.display.HTML at 0x1023c37d0>"
260        ]
261       }
262      ],
263      "prompt_number": 8
264     },
265     {
266      "cell_type": "markdown",
267      "metadata": {},
268      "source": [
269       "We can also combine aggregated results with raw results,\n",
270       "although the output might surprise you:"
271      ]
272     },
273     {
274      "cell_type": "code",
275      "collapsed": false,
276      "input": [
277       "%%sqlite survey.db\n",
278       "select person, count(*) from Survey where quant='sal' and reading<=1.0;"
279      ],
280      "language": "python",
281      "metadata": {},
282      "outputs": [
283       {
284        "html": [
285         "<table>\n",
286         "<tr><td>lake</td><td>7</td></tr>\n",
287         "</table>"
288        ],
289        "metadata": {},
290        "output_type": "display_data",
291        "text": [
292         "<IPython.core.display.HTML at 0x1023c37d0>"
293        ]
294       }
295      ],
296      "prompt_number": 9
297     },
298     {
299      "cell_type": "markdown",
300      "metadata": {},
301      "source": [
302       "Why does Lake's name appear rather than Roerich's or Dyer's?\n",
303       "The answer is that when it has to aggregate a field,\n",
304       "but isn't told how to,\n",
305       "the database manager chooses an actual value from the input set.\n",
306       "It might use the first one processed,\n",
307       "the last one,\n",
308       "or something else entirely.\n",
309       "\n",
310       "Another important fact is that when there are no values to aggregate,\n",
311       "aggregation's result is \"don't know\"\n",
312       "rather than zero or some other arbitrary value:"
313      ]
314     },
315     {
316      "cell_type": "code",
317      "collapsed": false,
318      "input": [
319       "%%sqlite survey.db\n",
320       "select person, max(reading), sum(reading) from Survey where quant='missing';"
321      ],
322      "language": "python",
323      "metadata": {},
324      "outputs": [
325       {
326        "html": [
327         "<table>\n",
328         "<tr><td>None</td><td>None</td><td>None</td></tr>\n",
329         "</table>"
330        ],
331        "metadata": {},
332        "output_type": "display_data",
333        "text": [
334         "<IPython.core.display.HTML at 0x1023c37d0>"
335        ]
336       }
337      ],
338      "prompt_number": 10
339     },
340     {
341      "cell_type": "markdown",
342      "metadata": {},
343      "source": [
344       "One final important feature of aggregation functions is that\n",
345       "they are inconsistent with the rest of SQL in a very useful way.\n",
346       "If we add two values,\n",
347       "and one of them is null,\n",
348       "the result is null.\n",
349       "By extension,\n",
350       "if we use `sum` to add all the values in a set,\n",
351       "and any of those values are null,\n",
352       "the result should also be null.\n",
353       "It's much more useful,\n",
354       "though,\n",
355       "for aggregation functions to ignore null values\n",
356       "and only combine those that are non-null.\n",
357       "This behavior lets us write our queries as:"
358      ]
359     },
360     {
361      "cell_type": "code",
362      "collapsed": false,
363      "input": [
364       "%%sqlite survey.db\n",
365       "select min(dated) from Visited;"
366      ],
367      "language": "python",
368      "metadata": {},
369      "outputs": [
370       {
371        "html": [
372         "<table>\n",
373         "<tr><td>1927-02-08</td></tr>\n",
374         "</table>"
375        ],
376        "metadata": {},
377        "output_type": "display_data",
378        "text": [
379         "<IPython.core.display.HTML at 0x1023cbe90>"
380        ]
381       }
382      ],
383      "prompt_number": 11
384     },
385     {
386      "cell_type": "markdown",
387      "metadata": {},
388      "source": [
389       "instead of always having to filter explicitly:"
390      ]
391     },
392     {
393      "cell_type": "code",
394      "collapsed": false,
395      "input": [
396       "%%sqlite survey.db\n",
397       "select min(dated) from Visited where dated is not null;"
398      ],
399      "language": "python",
400      "metadata": {},
401      "outputs": [
402       {
403        "html": [
404         "<table>\n",
405         "<tr><td>1927-02-08</td></tr>\n",
406         "</table>"
407        ],
408        "metadata": {},
409        "output_type": "display_data",
410        "text": [
411         "<IPython.core.display.HTML at 0x1023c9650>"
412        ]
413       }
414      ],
415      "prompt_number": 12
416     },
417     {
418      "cell_type": "markdown",
419      "metadata": {},
420      "source": [
421       "Aggregating all records at once doesn't always make sense.\n",
422       "For example,\n",
423       "suppose Gina suspects that there is a systematic bias in her data,\n",
424       "and that some scientists' radiation readings are higher than others.\n",
425       "We know that this doesn't work:"
426      ]
427     },
428     {
429      "cell_type": "code",
430      "collapsed": false,
431      "input": [
432       "%%sqlite survey.db\n",
433       "select person, count(reading), round(avg(reading), 2)\n",
434       "from  Survey\n",
435       "where quant='rad';"
436      ],
437      "language": "python",
438      "metadata": {},
439      "outputs": [
440       {
441        "html": [
442         "<table>\n",
443         "<tr><td>roe</td><td>8</td><td>6.56</td></tr>\n",
444         "</table>"
445        ],
446        "metadata": {},
447        "output_type": "display_data",
448        "text": [
449         "<IPython.core.display.HTML at 0x1023c45d0>"
450        ]
451       }
452      ],
453      "prompt_number": 13
454     },
455     {
456      "cell_type": "markdown",
457      "metadata": {},
458      "source": [
459       "because the database manager selects a single arbitrary scientist's name\n",
460       "rather than aggregating separately for each scientist.\n",
461       "Since there are only five scientists,\n",
462       "she could write five queries of the form:"
463      ]
464     },
465     {
466      "cell_type": "code",
467      "collapsed": false,
468      "input": [
469       "%%sqlite survey.db\n",
470       "select person, count(reading), round(avg(reading), 2)\n",
471       "from  Survey\n",
472       "where quant='rad'\n",
473       "and   person='dyer';"
474      ],
475      "language": "python",
476      "metadata": {},
477      "outputs": [
478       {
479        "html": [
480         "<table>\n",
481         "<tr><td>dyer</td><td>2</td><td>8.81</td></tr>\n",
482         "</table>"
483        ],
484        "metadata": {},
485        "output_type": "display_data",
486        "text": [
487         "<IPython.core.display.HTML at 0x1023c4790>"
488        ]
489       }
490      ],
491      "prompt_number": 14
492     },
493     {
494      "cell_type": "markdown",
495      "metadata": {},
496      "source": [
497       "but this would be tedious,\n",
498       "and if she ever had a data set with fifty or five hundred scientists,\n",
499       "the chances of her getting all of those queries right is small.\n",
500       "\n",
501       "What we need to do is\n",
502       "tell the database manager to aggregate the hours for each scientist separately\n",
503       "using a `group by` clause:"
504      ]
505     },
506     {
507      "cell_type": "code",
508      "collapsed": false,
509      "input": [
510       "%%sqlite survey.db\n",
511       "select   person, count(reading), round(avg(reading), 2)\n",
512       "from     Survey\n",
513       "where    quant='rad'\n",
514       "group by person;"
515      ],
516      "language": "python",
517      "metadata": {},
518      "outputs": [
519       {
520        "html": [
521         "<table>\n",
522         "<tr><td>dyer</td><td>2</td><td>8.81</td></tr>\n",
523         "<tr><td>lake</td><td>2</td><td>1.82</td></tr>\n",
524         "<tr><td>pb</td><td>3</td><td>6.66</td></tr>\n",
525         "<tr><td>roe</td><td>1</td><td>11.25</td></tr>\n",
526         "</table>"
527        ],
528        "metadata": {},
529        "output_type": "display_data",
530        "text": [
531         "<IPython.core.display.HTML at 0x1023c4110>"
532        ]
533       }
534      ],
535      "prompt_number": 15
536     },
537     {
538      "cell_type": "markdown",
539      "metadata": {},
540      "source": [
541       "`group by` does exactly what its name implies:\n",
542       "groups all the records with the same value for the specified field together\n",
543       "so that aggregation can process each batch separately.\n",
544       "Since all the records in each batch have the same value for `person`,\n",
545       "it no longer matters that the database manager\n",
546       "is picking an arbitrary one to display\n",
547       "alongside the aggregated `reading` values."
548      ]
549     },
550     {
551      "cell_type": "markdown",
552      "metadata": {},
553      "source": [
554       "Just as we can sort by multiple criteria at once,\n",
555       "we can also group by multiple criteria.\n",
556       "To get the average reading by scientist and quantity measured,\n",
557       "for example,\n",
558       "we just add another field to the `group by` clause:"
559      ]
560     },
561     {
562      "cell_type": "code",
563      "collapsed": false,
564      "input": [
565       "%%sqlite survey.db\n",
566       "select   person, quant, count(reading), round(avg(reading), 2)\n",
567       "from     Survey\n",
568       "group by person, quant;"
569      ],
570      "language": "python",
571      "metadata": {},
572      "outputs": [
573       {
574        "html": [
575         "<table>\n",
576         "<tr><td>None</td><td>sal</td><td>1</td><td>0.06</td></tr>\n",
577         "<tr><td>None</td><td>temp</td><td>1</td><td>-26.0</td></tr>\n",
578         "<tr><td>dyer</td><td>rad</td><td>2</td><td>8.81</td></tr>\n",
579         "<tr><td>dyer</td><td>sal</td><td>2</td><td>0.11</td></tr>\n",
580         "<tr><td>lake</td><td>rad</td><td>2</td><td>1.82</td></tr>\n",
581         "<tr><td>lake</td><td>sal</td><td>4</td><td>0.11</td></tr>\n",
582         "<tr><td>lake</td><td>temp</td><td>1</td><td>-16.0</td></tr>\n",
583         "<tr><td>pb</td><td>rad</td><td>3</td><td>6.66</td></tr>\n",
584         "<tr><td>pb</td><td>temp</td><td>2</td><td>-20.0</td></tr>\n",
585         "<tr><td>roe</td><td>rad</td><td>1</td><td>11.25</td></tr>\n",
586         "<tr><td>roe</td><td>sal</td><td>2</td><td>32.05</td></tr>\n",
587         "</table>"
588        ],
589        "metadata": {},
590        "output_type": "display_data",
591        "text": [
592         "<IPython.core.display.HTML at 0x1023c45d0>"
593        ]
594       }
595      ],
596      "prompt_number": 16
597     },
598     {
599      "cell_type": "markdown",
600      "metadata": {},
601      "source": [
602       "Note that we have added `person` to the list of fields displayed,\n",
603       "since the results wouldn't make much sense otherwise.\n",
604       "\n",
605       "Let's go one step further and remove all the entries\n",
606       "where we don't know who took the measurement:"
607      ]
608     },
609     {
610      "cell_type": "code",
611      "collapsed": false,
612      "input": [
613       "%%sqlite survey.db\n",
614       "select   person, quant, count(reading), round(avg(reading), 2)\n",
615       "from     Survey\n",
616       "where    person is not null\n",
617       "group by person, quant\n",
618       "order by person, quant;"
619      ],
620      "language": "python",
621      "metadata": {},
622      "outputs": [
623       {
624        "html": [
625         "<table>\n",
626         "<tr><td>dyer</td><td>rad</td><td>2</td><td>8.81</td></tr>\n",
627         "<tr><td>dyer</td><td>sal</td><td>2</td><td>0.11</td></tr>\n",
628         "<tr><td>lake</td><td>rad</td><td>2</td><td>1.82</td></tr>\n",
629         "<tr><td>lake</td><td>sal</td><td>4</td><td>0.11</td></tr>\n",
630         "<tr><td>lake</td><td>temp</td><td>1</td><td>-16.0</td></tr>\n",
631         "<tr><td>pb</td><td>rad</td><td>3</td><td>6.66</td></tr>\n",
632         "<tr><td>pb</td><td>temp</td><td>2</td><td>-20.0</td></tr>\n",
633         "<tr><td>roe</td><td>rad</td><td>1</td><td>11.25</td></tr>\n",
634         "<tr><td>roe</td><td>sal</td><td>2</td><td>32.05</td></tr>\n",
635         "</table>"
636        ],
637        "metadata": {},
638        "output_type": "display_data",
639        "text": [
640         "<IPython.core.display.HTML at 0x1023c4790>"
641        ]
642       }
643      ],
644      "prompt_number": 17
645     },
646     {
647      "cell_type": "markdown",
648      "metadata": {},
649      "source": [
650       "Looking more closely,\n",
651       "this query:\n",
652       "\n",
653       "1.  selected records from the `Survey` table\n",
654       "    where the `person` field was not null;\n",
655       "\n",
656       "2.  grouped those records into subsets\n",
657       "    so that the `person` and `quant` values in each subset\n",
658       "    were the same;\n",
659       "\n",
660       "3.  ordered those subsets first by `person`,\n",
661       "    and then within each sub-group by `quant`;\n",
662       "    and\n",
663       "\n",
664       "4.  counted the number of records in each subset,\n",
665       "    calculated the average `reading` in each,\n",
666       "    and chose a `person` and `quant` value from each\n",
667       "    (it doesn't matter which ones,\n",
668       "    since they're all equal)."
669      ]
670     },
671     {
672      "cell_type": "markdown",
673      "metadata": {},
674      "source": [
675       "### Challenges\n",
676       "\n",
677       "1.  How many temperature readings did Frank Pabodie record,\n",
678       "    and what was their average value?\n",
679       "\n",
680       "2.  The average of a set of values is the sum of the values\n",
681       "    divided by the number of values.\n",
682       "    Does this mean that the `avg` function returns 2.0 or 3.0\n",
683       "    when given the values 1.0, `null`, and 5.0?\n",
684       "\n",
685       "3.  We want to calculate the difference between\n",
686       "    each individual radiation reading\n",
687       "    and the average of all the radiation readings.\n",
688       "    We write the query:\n",
689       "\n",
690       "    ```\n",
691       "    select reading-avg(reading) from Survey where quant='rad';\n",
692       "    ```\n",
693       "\n",
694       "    What does this actually produce, and why?\n",
695       "\n",
696       "4.  The function `group_concat(field, separator)`\n",
697       "    concatenates all the values in a field\n",
698       "    using the specified separator character\n",
699       "    (or ',' if the separator isn't specified).\n",
700       "    Use this to produce a one-line list of scientists' names,\n",
701       "    such as:\n",
702       "\n",
703       "    ```\n",
704       "    William Dyer, Frank Pabodie, Anderson Lake, Valentina Roerich, Frank Danforth\n",
705       "    ```\n",
706       "\n",
707       "    Can you find a way to order the list by surname?"
708      ]
709     }
710    ],
711    "metadata": {}
712   }
713  ]
714 }