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

Aggregating Data Using the GROUP BY Clause<br />

54<br />

With ORDER BY, we have kind of taken things out of order compared with how the SELECT statement<br />

reads at the top of the chapter. Let’s review the overall statement structure:<br />

SELECT [TOP () [PERCENT] [WITH TIES]] <br />

[FROM ]<br />

[WHERE ]<br />

[GROUP BY ]<br />

[HAVING ]<br />

[ORDER BY ]<br />

[[FOR XML {RAW|AUTO|EXPLICIT|PATH [()]}[, XMLDATA][, ELEMENTS][, BINARY<br />

base 64]]<br />

[OPTION (, [, ...n])]<br />

Why, if ORDER BY comes last, did we look at it before the GROUP BY? There are two reasons:<br />

❑ ORDER BY is used far more often than GROUP BY, so I want you to have more practice with it.<br />

❑ I want to make sure that you understand that you can mix and match all of the clauses after the<br />

FROM clause, as long as you keep them in the order that <strong>SQL</strong> <strong>Server</strong> expects them (as defined in<br />

the syntax definition).<br />

The GROUP BY clause is used to aggregate information. Let’s look at a simple query without a GROUP BY.<br />

Let’s say that we want to know how many parts were ordered in a given set of orders:<br />

SELECT SalesOrderID, OrderQty<br />

FROM Sales.SalesOrderDetail<br />

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

This yields a result set of:<br />

SalesOrderID OrderQty<br />

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

43660 1<br />

43660 1<br />

43670 1<br />

43670 2<br />

43670 2<br />

43670 1<br />

43672 6<br />

43672 2<br />

43672 1<br />

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

Even though we’ve only asked for three orders, we’re seeing each individual line of detail from the<br />

orders. We can either get out our adding machine, or we can make use of the GROUP BY clause with an<br />

aggregator. In this case, we’ll use SUM():<br />

SELECT SalesOrderID, SUM(OrderQty)<br />

FROM Sales.SalesOrderDetail

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

Saved successfully!

Ooh no, something went wrong!