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.

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

GROUP BY SalesOrderID;<br />

This gets us what we were looking for:<br />

SalesOrderID<br />

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

43660 2<br />

43670 6<br />

43672 9<br />

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

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

As you would expect, the SUM function returns totals — but totals of what? We can easily supply an alias<br />

for our result. Let’s modify our query slightly to provide a column name for the output:<br />

SELECT SalesOrderID, SUM(OrderQty) AS TotalOrderQty<br />

FROM Sales.SalesOrderDetail<br />

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

GROUP BY SalesOrderID;<br />

This gets us the same basic output, but also supplies a header to the grouped column:<br />

SalesOrderID TotalOrderQty<br />

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

43660 2<br />

43670 6<br />

43672 9<br />

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

If you’re just trying to get some quick results, then there really is no need to alias the grouped column as<br />

we’ve done here, but many of your queries are going to be written to supply information to other elements<br />

of a larger program. The code that’s utilizing your queries will need some way of referencing your grouped<br />

column; aliasing your column to some useful name can be critical in that situation. We’ll examine aliasing<br />

a bit more shortly.<br />

If we didn’t supply the GROUP BY clause, the SUM would have been of all the values in all of the rows for<br />

the named column. In this case, however, we did supply a GROUP BY, and so the total provided by the<br />

SUM function is the total in each group.<br />

Note that when using a GROUP BY clause, all the columns in the SELECT list must<br />

either be aggregates (SUM, MIN/MAX, AVG, and so on) or columns included in the<br />

GROUP BY clause. Likewise, if you are using an aggregate in the SELECT list, your<br />

SELECT list must only contain aggregates, or there must be a GROUP BY clause.<br />

We can also group based on multiple columns. To do this we just add a comma and the next column<br />

name. Let’s say, for example, that we’re looking for the number of orders each salesperson has taken for<br />

55

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

Saved successfully!

Ooh no, something went wrong!