GROUP BY and ORDER BY
GROUP BY and ORDER BY
BY
Introduction
Aggregating data (also referred to as rolling
up, summarizing, or grouping data) is creating
some sort of total from a number of records.
Sum, min, max, count, and average are common
aggregate operations. In SQL you can group these
totals on any specified columns, allowing you to
control the scope of these aggregations easily.
Grouping Records
First, perform the simplest aggregation: count the
number of records in a table. Open the SQL editor and
get a count of records for station data:
Note that not all platforms support ordinal positions. With Oracle and SQL
Server, for example, you will have to rewrite the entire column name or
expression in the GROUP BY.
Ordering Records
Notice that the month column is not in a
natural sort we would expect. This is a good time
to bring up the ORDER BY operator, which you can
put at the end of a SQL statement (after any
WHERE and GROUP BY). If you wanted to sort by
year, and then month, you could just add this
command:
SELECT year, month, COUNT(*) AS record_count FROM station_data WHERE tornado =
GROUP BY month
SUM() is another common aggregate operation. To find the sum
of snow depth by year since 2000, run this query: