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.

Executing the preceding query provides these results:<br />

SalesPersonId MemberId<br />

1 4<br />

1 6<br />

1 7<br />

1 8<br />

1 9<br />

1 11<br />

1 14<br />

1 15<br />

2 4<br />

2 7<br />

2 9<br />

2 10<br />

3 1<br />

3 4<br />

3 5<br />

3 9<br />

3 11<br />

3 12<br />

3 13<br />

Identical SalesPersonId and MemberId records are now grouped, but the results still include members<br />

who placed only one order with a salesperson. You want only those customers who ordered more than<br />

once, so you need to count the number of customers in each group who ordered from a specific salesperson.<br />

If the MemberId appears more than once, that particular customer has ordered more than once from<br />

that salesperson:<br />

SELECT SalesPersonId, MemberId<br />

FROM Orders<br />

GROUP BY SalesPersonId, MemberId<br />

HAVING COUNT(MemberId) > 1<br />

ORDER BY SalesPersonId<br />

Advanced Queries<br />

Each group contains all the rows with the same salesperson and customer. The COUNT(MemberId) function<br />

counts the number of rows in each group, and the HAVING clause restricts the display of groups to<br />

only those where the count is more than 1 — that is, more than one order by the same customer with the<br />

same salesperson. This query provides the following results:<br />

279

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

Saved successfully!

Ooh no, something went wrong!