13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

256 Chapter 10 Working with Your <strong>MySQL</strong> Database<br />

In addition, you can sort on more than one column.You can also use column aliases or<br />

even their position numbers (for example, 3 is the third column in the table) instead of<br />

names.<br />

Grouping <strong>and</strong> Aggregating Data<br />

You may often want to know how many rows fall into a particular set or the average<br />

value of some column—say, the average dollar value per order. <strong>MySQL</strong> has a set of<br />

aggregate functions that are useful for answering this type of query.<br />

These aggregate functions can be applied to a table as a whole or to groups of data<br />

within a table.The most commonly used ones are listed in Table 10.3.<br />

Table 10.3<br />

Name<br />

Aggregate Functions in <strong>MySQL</strong><br />

Description<br />

AVG(column)<br />

COUNT(items)<br />

MIN(column)<br />

MAX(column)<br />

STD(column)<br />

STDDEV(column)<br />

SUM(column)<br />

Average of values in the specified column.<br />

If you specify a column, this will give you the number of non-NULL<br />

values in that column. If you add the word DISTINCT in front of the<br />

column name, you will get a count of the distinct values in that column<br />

only. If you specify COUNT(*), you will get a row count regardless<br />

of NULL values.<br />

Minimum of values in the specified column.<br />

Maximum of values in the specified column.<br />

St<strong>and</strong>ard deviation of values in the specified column.<br />

Same as STD(column).<br />

Sum of values in the specified column.<br />

Let’s look at some examples, beginning with the one mentioned earlier.You can calculate<br />

the average total of an order like this:<br />

select avg(amount)<br />

from orders;<br />

The output is something like this:<br />

+-------------+<br />

| avg(amount) |<br />

+-------------+<br />

| 54.985002 |<br />

+-------------+<br />

To get more detailed information, you can use the GROUP BY clause. It enables you to<br />

view the average order total by group—for example, by customer number.This information<br />

tells you which of your customers place the biggest orders:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!