Skip to Main Content
MySQL Cookbook
book

MySQL Cookbook

by Paul DuBois
October 2002
Intermediate to advanced content levelIntermediate to advanced
1024 pages
27h 26m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook

Summarizing with SUM( ) and AVG( )

Problem

You need to add up a set of numbers or find their average.

Solution

Use the SUM( ) or AVG( ) functions.

Discussion

SUM( ) and AVG( ) produce the total and average (mean) of a set of values:

  • What is the total amount of mail traffic and the average size of each message?

    mysql> SELECT SUM(size) AS 'total traffic',
        -> AVG(size) AS 'average message size'
        -> FROM mail;
    +---------------+----------------------+
    | total traffic | average message size |
    +---------------+----------------------+
    |       3798185 |          237386.5625 |
    +---------------+----------------------+
  • How many miles did the drivers in the driver_log table travel? What was the average miles traveled per day?

    mysql> SELECT SUM(miles) AS 'total miles',
        -> AVG(miles) AS 'average miles/day'
        -> FROM driver_log;
    +-------------+-------------------+
    | total miles | average miles/day |
    +-------------+-------------------+
    |        2166 |          216.6000 |
    +-------------+-------------------+
  • What is the total population of the United States?

    mysql> SELECT SUM(pop) FROM states;
    +-----------+
    | SUM(pop)  |
    +-----------+
    | 248102973 |
    +-----------+

    (The value represents the population reported for April, 1990. The figure shown here differs from the U.S. population reported by the U.S. Census Bureau, because the states table doesn’t contain a count for Washington, D.C.)

SUM( ) and AVG( ) are strictly numeric functions, so they can’t be used with strings or temporal values. On the other hand, sometimes you can convert non-numeric ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Reference Manual

MySQL Reference Manual

Michael Widenius, David Axmark, Kaj Arno
High Performance MySQL

High Performance MySQL

Jeremy D. Zawodny, Derek J. Balling
MySQL Stored Procedure Programming

MySQL Stored Procedure Programming

Guy Harrison, Steven Feuerstein

Publisher Resources

ISBN: 0596001452Catalog PageErrata