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.

Let’s say, for example, that we wanted a list of the IDs for all of the products that we have sold at<br />

least 30 of in an individual sale (more than 30 at one time). We can easily get that information from the<br />

SalesOrderDetail table with the following query:<br />

SELECT ProductID<br />

FROM Sales.SalesOrderDetail<br />

WHERE OrderQty > 30;<br />

What we get back is one row matching the ProductID for every row in the SalesOrderDetail table<br />

that has an order quantity that is more than 30:<br />

ProductID<br />

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

709<br />

863<br />

863<br />

863<br />

863<br />

863<br />

863<br />

863<br />

715<br />

863<br />

...<br />

...<br />

869<br />

869<br />

867<br />

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

While this meets your needs from a technical standpoint, it doesn’t really meet your needs from a reality<br />

standpoint. Look at all those duplicate rows! While we could look through and see which products sold<br />

more than 30 at a time, the number of rows returned and the number of duplicates can quickly become<br />

overwhelming. Like the problems we’ve discussed before, we have an answer. It comes in the form of<br />

the DISTINCT predicate on your SELECT statement.<br />

Try re-running the query with a slight change:<br />

SELECT DISTINCT ProductID<br />

FROM Sales.SalesOrderDetail<br />

WHERE OrderQty > 30;<br />

Now you come up with a true list of the ProductIDs that sold more than 30 at one time:<br />

ProductID<br />

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

863<br />

869<br />

709<br />

864<br />

867<br />

715<br />

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

Chapter 3: The Foundation Statements of T-<strong>SQL</strong><br />

65

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

Saved successfully!

Ooh no, something went wrong!