20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Executing the <strong>SQL</strong> returns seven distinct values. The following Try It Out puts your knowledge of counting<br />

and grouping results to the test.<br />

Try It Out Counting and Grouping Results<br />

The film club’s chairperson wants to know which film categories are most popular among club members.<br />

The list must be in order from the most popular category to the least popular category.<br />

1. Execute the following <strong>SQL</strong> to obtain the grouped results:<br />

SELECT Category, COUNT(FavCategory.CategoryId) AS Popularity<br />

FROM FavCategory INNER JOIN Category<br />

ON FavCategory.CategoryId = Category.CategoryId<br />

GROUP BY Category<br />

ORDER BY Popularity DESC;<br />

Note that the preceding code won’t work in MS Access unless you change the ORDER BY clause<br />

as shown here:<br />

ORDER BY COUNT(FavCategory.CategoryId) DESC;<br />

How It Works<br />

This <strong>SQL</strong> statement is a little trickier than what you’ve seen so far. Perhaps the hardest part with <strong>SQL</strong> is<br />

not the actual code but rather working out how to get the information you want, determining where it’s<br />

coming from, and then translating that into <strong>SQL</strong>. If you find that the <strong>SQL</strong> necessary to answer a particular<br />

question is a little bit tricky, it’s best to start simple and build the code up. For example, a good start<br />

in answering the film club chairperson’s query could be simply to select all the CategoryIds in the<br />

FavCategory table:<br />

SELECT FavCategory.CategoryId<br />

FROM FavCategory;<br />

After selecting the categories, you can count the categories:<br />

SELECT COUNT(FavCategory.CategoryId)<br />

FROM FavCategory;<br />

This query returns 21, which tells you nothing except that there are 21 rows in the table. However, you<br />

want to know how many rows there are in each category, so you need to group the results by CategoryId:<br />

SELECT COUNT(FavCategory.CategoryId)<br />

FROM FavCategory<br />

GROUP BY FavCategory.CategoryId;<br />

Executing this code gives a count for each category, but it contains only the CategoryId, so you need to<br />

join the FavCategory and Category tables together to get the names of the category groups:<br />

SELECT Category, COUNT(FavCategory.CategoryId) AS Popularity<br />

FROM FavCategory INNER JOIN Category<br />

ON FavCategory.CategoryId = Category.CategoryId<br />

GROUP BY Category;<br />

Grouping and Aggregating Data<br />

195

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

Saved successfully!

Ooh no, something went wrong!