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.

immediately after the GROUP BY statement. For example, the following <strong>SQL</strong> creates a list of cities that<br />

have three or more members in them:<br />

SELECT City<br />

FROM MemberDetails<br />

GROUP BY City<br />

HAVING COUNT(MemberId) >= 3;<br />

The HAVING clause applies on a per-group basis, filtering out those groups that don’t match the condition,<br />

whereas the WHERE clause applies on a per-record basis, filtering out records. The results for the<br />

preceding <strong>SQL</strong> are shown in the following table:<br />

City<br />

Orange Town<br />

If you take away the HAVING clause and add details of the COUNT(MemberId), your <strong>SQL</strong> is as follows:<br />

SELECT City, COUNT(MemberId)<br />

FROM MemberDetails<br />

GROUP BY City;<br />

You can see how the database gets its results:<br />

City COUNT(MemberId)<br />

NULL 1<br />

Big City 2<br />

Dover 1<br />

New Town 1<br />

Orange Town 4<br />

Townsville 2<br />

Windy Village 2<br />

Grouping and Aggregating Data<br />

You can see from the list that only Big City and New Town have three or more members. It’s important<br />

to note that the WHERE clause restricts the record set that the GROUP BY clause works with. However, the<br />

HAVING clause affects only the displayed final results. Now that you’re acquainted with the HAVING<br />

clause’s functions, the following Try It Out shows you how to use it in <strong>SQL</strong> statements.<br />

Try It Out Working with the HAVING Clause<br />

1. In an earlier example, the film club’s chairperson wanted to know how many members listed<br />

each film category as their favorite. The chairperson also wanted the list ordered from the most<br />

popular to the least popular category. However, now the chairperson wants the list to include<br />

only those categories where four or more members listed that category as their favorite. Execute<br />

the following <strong>SQL</strong> to answer the chairperson’s question:<br />

203

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

Saved successfully!

Ooh no, something went wrong!