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.

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

194<br />

…<br />

30116 51106 2003-07-01 00:00:00.000<br />

30117 43865 2001-08-01 00:00:00.000<br />

30118 47378 2002-09-01 00:00:00.000<br />

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

As previously stated, don’t worry if your results are slightly different from those shown here — it just means<br />

you’ve been playing around with the AdventureWorks<strong>2008</strong> data a little more or a little less than I have.<br />

The fact that we are building two completely separate result sets here is emphasized by the fact that you<br />

see two different row(s) affected in the results. That, more often than not, has a negative impact on<br />

performance. We’ll explore this further after we explore our options some more.<br />

Sometimes using this multiple-query approach is simply the only way to get things done without using<br />

a cursor — this is not one of those times.<br />

OK, so if we want this to run in a single query, we need to find a way to look up each individual customer.<br />

We can do this by making use of an inner query that performs a lookup based on the current<br />

CustomerID in the outer query. We will then need to return a value back out to the outer query so it can<br />

match things up based on the earliest order date.<br />

It looks like this:<br />

SELECT soh1.CustomerID, soh1.SalesOrderID, soh1.OrderDate<br />

FROM Sales.SalesOrderHeader soh1<br />

WHERE soh1.OrderDate = (SELECT Min(soh2.OrderDate)<br />

FROM Sales.SalesOrderHeader soh2<br />

WHERE soh2.CustomerID = soh1.CustomerID)<br />

ORDER BY CustomerID;<br />

With this, we get back the same 19,134 rows:<br />

CustomerID SalesOrderID OrderDate<br />

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

11000 43793 2001-07-22 00:00:00.000<br />

11001 43767 2001-07-18 00:00:00.000<br />

11002 43736 2001-07-10 00:00:00.000<br />

…<br />

…<br />

30116 51106 2003-07-01 00:00:00.000<br />

30117 43865 2001-08-01 00:00:00.000<br />

30118 47378 2002-09-01 00:00:00.000<br />

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

There are a few key things to notice in this query:<br />

❑ We see only one row(s) affected line — giving us a good clue that only one query plan had<br />

to be executed.<br />

❑ The outer query (in this example) looks pretty much just like a nested subquery. The inner<br />

query, however, has an explicit reference to the outer query (notice the use of the o1 alias).

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

Saved successfully!

Ooh no, something went wrong!