17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

So let’s take this now and apply it to our requirements. Again, what we want are the account numbers<br />

and territories of all the companies that have ordered both HL Mountain Rear Wheel and HL Mountain<br />

Front Wheel. So our query should look something like this:<br />

SELECT DISTINCT sc.AccountNumber, sst.Name<br />

FROM Sales.Customer AS sc<br />

JOIN Sales.SalesTerritory sst<br />

ON sc.TerritoryID = sst.TerritoryID<br />

JOIN<br />

(SELECT CustomerID<br />

FROM Sales.SalesOrderHeader soh<br />

JOIN Sales.SalesOrderDetail sod<br />

ON soh.SalesOrderID = sod.SalesOrderID<br />

JOIN Production.Product pp<br />

ON sod.ProductID = pp.ProductID<br />

WHERE pp.Name = ‘HL Mountain Rear Wheel’) AS dt1<br />

ON sc.CustomerID = dt1.CustomerID<br />

JOIN<br />

(SELECT CustomerID<br />

FROM Sales.SalesOrderHeader soh<br />

JOIN Sales.SalesOrderDetail sod<br />

ON soh.SalesOrderID = sod.SalesOrderID<br />

JOIN Production.Product pp<br />

ON sod.ProductID = pp.ProductID<br />

WHERE Name = ‘HL Mountain Front Wheel’) AS dt2<br />

ON sc.CustomerID = dt2.CustomerID;<br />

We wind up with 58 accounts:<br />

AccountNumber Name<br />

------------- ----------------------------<br />

AW00029484 Southeast<br />

AW00029490 Northwest<br />

AW00029499 Canada<br />

…<br />

…<br />

AW00030108 Canada<br />

AW00030113 United Kingdom<br />

AW00030118 Central<br />

(58 row(s) affected)<br />

Chapter 7: Adding More to Our Queries<br />

If you want to check things out on this, just run the queries for the two derived tables separately and<br />

compare the results.<br />

For this particular query, I needed to use the DISTINCT keyword. If I didn’t, then I would have potentially<br />

received multiple rows for each customer — for example, AW00029771 has ordered the HL Mountain<br />

Rear Wheel twice, so I would have gotten one record for each. I only asked which customers had ordered<br />

both, not how many had they ordered.<br />

199

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

Saved successfully!

Ooh no, something went wrong!