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.

Appendix A<br />

Your answer may differ, as there’s more than one way to answer this question, but that doesn’t matter as<br />

long as the results are the same. The right outer join obtains all rows from the Category table, regardless<br />

of whether there is a matching CategoryId in the FavCategory table. If there is no matching CategoryId<br />

in the FavCategory table, then it means that no member has chosen that category as their favorite. When<br />

this happens, FavCategory.CategoryId has a NULL value, so all you need to do is add a WHERE clause<br />

that specifies that FavCategory.CategoryId must be NULL, and you ensure that only those categories<br />

not picked as a favorite are included in the results. The final results are as follows:<br />

Category<br />

Film Noir<br />

Chapter 8<br />

Exercise 1 Solution<br />

384<br />

Obtaining the CategoryId, name, and total cost of films in a particular category is fairly easy. The difficult<br />

part is obtaining the count of how many members put that category down as one of their favorites.<br />

For this, you should use a subquery in the SELECT statement’s column listing.<br />

SELECT Category.Category,<br />

SUM(DVDPrice) AS “Total Cost For Category”,<br />

(SELECT COUNT(*) FROM FavCategory<br />

WHERE FavCategory.CategoryId =<br />

Category.CategoryId) AS “Members Favorite Category”<br />

FROM Films INNER JOIN Category<br />

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

WHERE Films.AvailableOnDVD = ‘Y’<br />

GROUP BY Category.CategoryId, Category.Category;<br />

In the preceding query, the following subquery obtains the count of how many members listed that category<br />

as their favorite:<br />

(SELECT COUNT(*) FROM FavCategory<br />

WHERE FavCategory.CategoryId = Category.CategoryId)<br />

The subquery is joined to the outer query on the CategoryId columns in the FavCategory and Category<br />

tables.<br />

Notice that because the subquery references the CategoryId from the Category table in the main query,<br />

you must include it in the GROUP BY clause.

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

Saved successfully!

Ooh no, something went wrong!