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 3: The Foundation Statements of T-<strong>SQL</strong><br />

58<br />

And you come up with this:<br />

SalesOrderID<br />

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

43660 1<br />

43670 2<br />

43672 6<br />

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

What if, however, we wanted both the MIN and the MAX? Simple! Just use both in your query:<br />

SELECT SalesOrderID, MIN(OrderQty), MAX(OrderQty)<br />

FROM Sales.SalesOrderDetail<br />

WHERE SalesOrderID IN (43660, 43670, 43672)<br />

GROUP BY SalesOrderID;<br />

Now, this will yield an additional column and a bit of a problem:<br />

SalesOrderID<br />

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

43660 1 1<br />

43670 1 2<br />

43672 1 6<br />

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

Can you spot the issue here? We’ve gotten back everything that we’ve asked for, but now that we have<br />

more than one aggregate column, we have a problem identifying which column is which. Sure, in this<br />

particular example we can be sure that the columns with the largest numbers are the columns generated<br />

by the MAX and the smallest by the MIN. The answer to which column is which is not always so apparent,<br />

so let’s make use of an alias. An alias allows you to change the name of a column in the result set, and<br />

you can create it by using the AS keyword:<br />

SELECT SalesOrderID, MIN(OrderQty) AS MinOrderQty, MAX(OrderQty) AS MaxOrderQty<br />

FROM Sales.SalesOrderDetail<br />

WHERE SalesOrderID IN (43660, 43670, 43672)<br />

GROUP BY SalesOrderID;<br />

Now our results are somewhat easier to make sense of:<br />

SalesOrderID MinOrderQty MaxOrderQty<br />

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

43660 1 1<br />

43670 1 2<br />

43672 1 6<br />

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

It’s worth noting that the AS keyword is actually optional. Indeed, there was a time (prior to version 6.5<br />

of <strong>SQL</strong> <strong>Server</strong>) when it wasn’t even a valid keyword. If you like, you can execute the same query as

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

Saved successfully!

Ooh no, something went wrong!