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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Note that I’m deliberately eliminating the rows with no discount (that’s SpecialOfferID 1). This query<br />

yields 243 rows — each with an associated ProductID:<br />

SpecialOfferID Description DiscountPct ProductID<br />

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

2 Volume Discount 11 to 14 0.02 707<br />

2 Volume Discount 11 to 14 0.02 708<br />

2 Volume Discount 11 to 14 0.02 709<br />

2 Volume Discount 11 to 14 0.02 711<br />

…<br />

…<br />

…<br />

…<br />

16 Mountain-500 Silver Clearance 0.40 986<br />

16 Mountain-500 Silver Clearance 0.40 987<br />

16 Mountain-500 Silver Clearance 0.40 988<br />

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

Think about this, though. We wanted results based on the special offers we have — not which ones were<br />

actually in use. This query only gives us special offers that have products utilizing the offer — it doesn’t<br />

answer the question!<br />

What we need is something that’s going to return every special offer and the product ids where applicable.<br />

Try It Out Outer JOINs<br />

In order to return every special offer and the products where applicable, we need to change only the<br />

JOIN type in the query:<br />

SELECT sso.SpecialOfferID, Description, DiscountPct, ProductID<br />

FROM Sales.SpecialOffer sso<br />

LEFT OUTER JOIN Sales.SpecialOfferProduct ssop<br />

ON sso.SpecialOfferID = ssop.SpecialOfferID<br />

WHERE sso.SpecialOfferID != 1<br />

This yields similar results, but with one rather important difference:<br />

SpecialOfferID Description DiscountPct ProductID<br />

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

2 Volume Discount 11 to 14 0.02 707<br />

2 Volume Discount 11 to 14 0.02 708<br />

2 Volume Discount 11 to 14 0.02 709<br />

2 Volume Discount 11 to 14 0.02 711<br />

…<br />

…<br />

6 Volume Discount over 60 0.20 NULL<br />

…<br />

…<br />

16 Mountain-500 Silver Clearance 0.40 986<br />

16 Mountain-500 Silver Clearance 0.40 987<br />

Chapter 4: JOINs<br />

93

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

Saved successfully!

Ooh no, something went wrong!