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.

Chapter 8<br />

4. You should receive the following results:<br />

Category<br />

Thriller<br />

War<br />

Sci-fi<br />

Historical<br />

How It Works<br />

In the first step, you simply selected all the category names from the Category table — the main table<br />

from which the data is extracted. The subqueries come in Step 2 to filter the results.<br />

In Step 2, begin with the rating first. Information about films’ ratings is contained in the Films table, but<br />

all you want to know is whether there are films in a particular category that have a rating higher than 3.<br />

You’re not interested in knowing the names of the films, so you used an EXISTS operator with a subquery<br />

that returns a list of films rated higher than 3.<br />

Next, you linked the outer and inner queries using the CategoryId column in the Category and Films<br />

tables. Now, if for a particular category there are films rated higher than 3, the subquery returns rows<br />

and EXISTS evaluates to true.<br />

Finally, you used another subquery, nested inside the other subquery. This innermost subquery counts<br />

how many members like a particular category; then in the WHERE clause of the outer subquery, you check<br />

to see whether that value is 3 or more.<br />

Using the HAVING Clause with Subqueries<br />

252<br />

Chapter 5 first introduced the HAVING clause, which is used to filter the groups displayed in a results set<br />

when a GROUP BY clause has been used. For example, to get a list of cities where the average year of<br />

birth of members in each city is greater than 1990, you could use the HAVING clause like this:<br />

SELECT City<br />

FROM MemberDetails<br />

GROUP BY City<br />

HAVING AVG(YEAR(DateOfBirth)) > 1990;<br />

The preceding query compares against an actual value, 1990. A subquery is useful where you want to<br />

compare against a value extracted from the database itself rather than a predetermined value. For example,<br />

you might be asked to create a list of cities where the average year of birth is later than the average<br />

for the membership as a whole. To do this, you could use a HAVING clause plus a subquery that finds out<br />

the average year of birth of members:<br />

SELECT City<br />

FROM MemberDetails<br />

GROUP BY City<br />

HAVING AVG(YEAR(DateOfBirth)) ><br />

(SELECT AVG(YEAR(DateOfBirth)) FROM MemberDetails);

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

Saved successfully!

Ooh no, something went wrong!