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.

The results from the query are as follows:<br />

Category Total Cost For Category Members Favorite Category<br />

Thriller 15.98 3<br />

Romance 12.99 2<br />

Horror 18.94 3<br />

War 15.99 4<br />

Sci-fi 15.99 3<br />

Historical 41.97 3<br />

Exercise 2 Solution<br />

All the hard work in creating this query is in the WHERE clause. There are two important conditions for<br />

the WHERE clause: that a town must have two or more members, and that the town must not currently be<br />

listed in the Location table. The WHERE clause is broken down into two subqueries, one nested inside the<br />

other. The outer subquery returns the number of members living in a particular city. The inner subquery<br />

returns all rows from the Location table that match the city name and state:<br />

SELECT City, State FROM MemberDetails MD1<br />

WHERE (SELECT COUNT(*) from MemberDetails MD2<br />

WHERE NOT EXISTS (SELECT * FROM Location L1 WHERE L1.City = MD2.City AND L1.State =<br />

MD2.State)<br />

AND MD1.City = MD2.City AND MD1.State = MD2.State<br />

GROUP BY City, State) >= 2<br />

GROUP BY City, State;<br />

The nested inner subquery is this:<br />

(SELECT * FROM Location AS L1 WHERE L1.City = MD2.City AND L1.State = MD2.State)<br />

If this returns rows, then it means that the city already exists in the Location table, but because you want<br />

only cities not already in that table, use a NOT EXISTS operator in the outer subquery to remove those<br />

cities from the results.<br />

The outer subquery is as follows:<br />

Exercise Answers<br />

(SELECT COUNT(*) from MemberDetails MD2<br />

WHERE NOT EXISTS (SELECT * FROM Location L1 WHERE L1.City = MD2.City AND L1.State =<br />

MD2.State)<br />

AND MD1.City = MD2.City AND MD1.State = MD2.State<br />

GROUP BY City, State)<br />

This <strong>SQL</strong> returns the number of members living in a city, where the city does not exist in the Location<br />

table. In the main query, you then check to see that this value is 2 or more:<br />

385

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

Saved successfully!

Ooh no, something went wrong!