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.

AVG<br />

This one is for computing averages. Let’s try running the order quantity query we ran before, but now<br />

we’ll modify it to return the average quantity per order, rather than the total for each order:<br />

SELECT SalesOrderID, AVG(OrderQty)<br />

FROM Sales.SalesOrderDetail<br />

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

GROUP BY SalesOrderID;<br />

Notice that our results changed substantially:<br />

SalesOrderID<br />

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

43660 1<br />

43670 1<br />

43672 3<br />

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

You can check the math — on order number 43672 there were 3 line items totaling 9 altogether (9 / 3 = 3).<br />

MIN/MAX<br />

Bet you can guess these two. Yes, these grab the minimum and maximum amounts for each grouping for<br />

a selected column. Again, let’s use that same query modified for the MIN function:<br />

SELECT SalesOrderID, MIN(OrderQty)<br />

FROM Sales.SalesOrderDetail<br />

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

GROUP BY SalesOrderID;<br />

Which gives the following results:<br />

SalesOrderID<br />

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

43660 1<br />

43670 1<br />

43672 1<br />

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

Modify it one more time for the MAX function:<br />

SELECT SalesOrderID, MAX(OrderQty)<br />

FROM Sales.SalesOrderDetail<br />

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

GROUP BY SalesOrderID;<br />

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

57

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

Saved successfully!

Ooh no, something went wrong!