Lesson 4 of 13 · 16 min

Grouping by several columns

By the end of this lesson you can group by two or more columns or expressions, predict how many rows the result will have, and choose the grain a report needs.

GROUP BY channel makes one group per channel. GROUP BY channel, status makes one group per combination of channel and status: (web, delivered), (web, cancelled), (app, delivered) and so on. Two rows land in the same group only if they agree on every grouping column.

The set of grouping columns defines the grain of the result: what one output row represents. Here, one row = one channel-and-status pair. Before writing a breakdown, say the grain out loud: “one row per year and channel”. That sentence is your GROUP BY.

Included with a Formula Quest membership

This lesson, its 4 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.

Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons