20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

Executing the final <strong>SQL</strong> provides the final results, shown in the following table:<br />

Category Popularity<br />

War 4<br />

Notice also that the ORDER BY clause must come last in the SELECT statement, otherwise an error occurs.<br />

Summary<br />

This chapter was all about summarizing and aggregating data, rather than getting results based on individual<br />

records. Central to this concept was the GROUP BY statement, which does the following:<br />

❑ Enables results to be based on groups of common data<br />

❑ Allows the aggregation and summary of those groups when used in conjunction with <strong>SQL</strong>’s<br />

aggregate functions such as COUNT(), SUM(), AVG(), MAX(), and MIN()<br />

The chapter examined thoroughly each of the aggregation functions, including the following:<br />

❑ COUNT(), which counts the number of record in the results set.<br />

Grouping and Aggregating Data<br />

❑ SUM(), which adds together the value of the specified column or expression for each record in<br />

the results set. SUM() works only with numerical data types.<br />

❑ AVG(), which finds the average value for a particular column for each record in a results set.<br />

Like SUM(), AVG() works only with numerical data types.<br />

❑ MAX() and MIN(), which find the lowest or highest value for a column in a results set. MAX()<br />

and MIN() work with date, time, character, and numerical data types.<br />

Finally, this chapter explored the HAVING clause, which filters out the result of groups using various conditions,<br />

much like a WHERE clause does for a FROM statement. Whereas the WHERE clause filters records,<br />

the HAVING clause filters groups found by the GROUP BY clause.<br />

The next chapter returns to joining tables, looks at subqueries, and shows you how to create complex<br />

queries.<br />

Exercises<br />

1. The film club’s chairperson decides that she’d like a list showing all the film costs broken down<br />

by film category and detailing how many films the club would have to buy in each category.<br />

She also wants you to factor in a 10% sales tax into the cost of each DVD. Change the results to<br />

list only those categories where one DVD is listed.<br />

2. Write a <strong>SQL</strong> query that finds out the highest and lowest ratings for each film category.<br />

205

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

Saved successfully!

Ooh no, something went wrong!