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.

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

Romance 1 14.289<br />

Sci-fi 1 14.289<br />

War 1 14.289<br />

Exercise 2 Solution<br />

The <strong>SQL</strong> required is as follows:<br />

SELECT Category, MAX(Rating) AS “Highest Rated”, MIN(Rating) AS “Lowest Rated”<br />

FROM Films INNER JOIN Category<br />

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

GROUP BY Category;<br />

Executing the query produces the results shown in the following table:<br />

Category Highest Rated Lowest Rated<br />

Historical 5 3<br />

Horror 2 1<br />

Romance 4 4<br />

Sci-fi 5 1<br />

Thriller 4 1<br />

War 5 2<br />

The necessary data comes from the Films and Category tables, which have been joined using an INNER<br />

JOIN on the CategoryId field. The results are grouped by the Category column, and the highest and lowest<br />

values for each group are obtained using the MAX() and MIN() functions.<br />

Chapter 7<br />

Exercise 1 Solution<br />

The following is the <strong>SQL</strong> that answers the question:<br />

Exercise Answers<br />

SELECT C1.Category, MD1.FirstName, MD1.LastName, MD2.FirstName, MD2.LastName<br />

FROM FavCategory FC1 INNER JOIN FavCategory FC2<br />

ON FC1.CategoryId = FC2.CategoryId<br />

INNER JOIN Category C1 ON C1.CategoryId = FC1.CategoryId<br />

INNER JOIN MemberDetails MD1 ON MD1.MemberId = FC1.MemberId<br />

INNER JOIN MemberDetails MD2 ON MD2.MemberId = FC2.MemberId<br />

WHERE FC1.MemberId < FC2.MemberId;<br />

381

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

Saved successfully!

Ooh no, something went wrong!