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 />

380<br />

You might receive slightly different results after the decimal point due to rounding errors by database<br />

systems.<br />

As with all of the more complex queries, start simple and build up. The first job is identifying which<br />

tables contain the data needed to answer the question. With this example, the Films table contains the<br />

price and film category information. However, you want to display the category name rather than just<br />

an ID, and name data comes from the Category table. Use a FROM statement to join the two tables, linked<br />

by the CategoryId, which is the primary key in the Category table and a foreign key in the Films table:<br />

FROM Films<br />

INNER JOIN Category<br />

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

WHERE AvailableOnDVD = ‘Y’;<br />

Add a WHERE clause that includes only records where the AvailableOnDVD field is Y, as there’s no point<br />

counting films that are not available on DVD.<br />

The question requires that the results be grouped into categories and that the results should return the<br />

category name, the number of DVDs in the category, and the total price for the DVDs in each category<br />

group. Therefore, you need to add a GROUP BY clause, grouping by Category:<br />

FROM Films<br />

INNER JOIN Category<br />

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

WHERE AvailableOnDVD = ‘Y’<br />

GROUP BY Category;<br />

Finally, add the columns and expressions that make up the final results: the Category column, the count of<br />

the number of DVDs per group, and the total price of the DVDs in that group including a 10% sales tax:<br />

SELECT Category, COUNT(DVDPrice), SUM(DVDPrice * 1.1)<br />

FROM Films<br />

INNER JOIN Category<br />

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

WHERE AvailableOnDVD = ‘Y’<br />

GROUP BY Category;<br />

The second part of the question asks you to limit the results to just those groups where the number of<br />

DVDs is just one. To do this, add a HAVING clause with a condition that allows only groups with one<br />

record in them to be included in the final results:<br />

SELECT Category, COUNT(DVDPrice), SUM(DVDPrice * 1.1)<br />

FROM Films<br />

INNER JOIN Category<br />

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

WHERE AvailableOnDVD = ‘Y’<br />

GROUP BY Category<br />

HAVING COUNT(DVDPrice) = 1;<br />

The final <strong>SQL</strong> provides the results in the following table:

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

Saved successfully!

Ooh no, something went wrong!