Grouping data

The ability to group items of data is very useful when attempting to make summarized reports. SQL features a clause called GROUP BY that allows you to group rows that share a common set of values and apply group functions to them.

A good example of this operation is where you want to total the values contained within a column in a table. In this instance, you would use the sum( ) grouping function in the following way to calculate the total value of orders taken on a given date:

SELECT order_date, sum( net ), sum( vat ), sum( total )
FROM sales
GROUP BY order_date

As with ORDER BY, groupings can be chained together in a comma-separated list to create complex subgroupings of columns.

Get Programming the Perl DBI now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.