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.

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

But let’s say, just for instance, that we are regularly purging data from the system, and we still want to<br />

ask this same question as part of an automated report.<br />

Since it’s going to be automated, we can’t run a query to find out what the first date in the system is and<br />

manually plug that into our query — or can we? Actually, the answer is: “Yes, we can,” by putting it all<br />

into just one statement:<br />

SELECT DISTINCT soh.OrderDate, sod.ProductID<br />

FROM Sales.SalesOrderHeader soh<br />

JOIN Sales.SalesOrderDetail sod<br />

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

WHERE OrderDate = (SELECT MIN(OrderDate) FROM Sales.SalesOrderHeader);<br />

It’s just that quick and easy. The inner query (SELECT MIN...) retrieves a single value for use in the<br />

outer query. Since we’re using an equal sign, the inner query absolutely must return only one column<br />

from one single row or you will get a runtime error.<br />

Notice that I added the order date to this new query. While it did not have to be there for the query to<br />

report the appropriate ProductID's, it does clarify what date those ProductID's are from. Under the<br />

first query, we knew what date because we had explicitly said it, but under this new query, the date is<br />

data driven, so it is often worthwhile to provide it as part of the result.<br />

Nested Queries Using Subqueries That Return Multiple Values<br />

190<br />

Perhaps the most common of all subqueries that are implemented in the world are those that retrieve<br />

some form of domain list and use it as criteria for a query.<br />

For this one, let’s revisit a problem we looked at in Chapter 4 when we were examining outer joins.<br />

What you want is a list of all the products that have special offers.<br />

We might write something like this:<br />

SELECT ProductID, Name<br />

FROM Production.Product<br />

WHERE ProductID IN (<br />

SELECT ProductID FROM Sales.SpecialOfferProduct);<br />

This returns 295 rows:<br />

ProductID Name<br />

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

680 HL Road Frame - Black, 58<br />

706 HL Road Frame - Red, 58<br />

707 Sport-100 Helmet, Red<br />

…<br />

…<br />

997 Road-750 Black, 44<br />

998 Road-750 Black, 48<br />

999 Road-750 Black, 52<br />

(295 row(s) affected)

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

Saved successfully!

Ooh no, something went wrong!